Get reference to class that called virtual method - c#

Is it possible to get a reference to the class that called a virtual method, from within the method defined in the abstract class?
Basically, I have an abstract class, let's say BaseAction, and this contains a virtual method, called RetrieveData:
public abstract class BaseAction
{
protected virtual void RetrieveData()
{
}
}
in the implementation, I pass this virtual method into a method as an Action, something to this effect:
public class Action: BaseAction
{
public Action()
{
ActionStatement(RetrieveData);
}
}
Is is possible to get a reference to Action class, in the RetrieveData method without having to override it in the Action class, something to this effect:
public abstract class BaseAction
{
protected virtual void RetrieveData()
{
// using reflection to get a handle on instance of Action?
}
}
The reason for this is, that I want to use this virtual method in various different type of classes, each one having an ID field which needs to be modified, but I don't want to override this virtual method in each of the 20+ action classes, just to change the ID field.
I'd like this to happen in the base class, to limit the amount of code duplication.

You don't need reflection to this. You have many options:
If the ID field is common in each implemented class, just declare it in the abstract class and change the value in the RetrieveData() method.
public abstract class BaseAction
{
protected int ID;
protected virtual void RetrieveData()
{
}
}
If the ID field is not common across all implemented classes, you can add an abstract method and use that method to access the ID property.
public abstract class BaseAction
{
protected abstract ChangeID(int value);
protected virtual void RetrieveData()
{
//Do your stuff
ChangeID(<with-new-value>);
}
}
public class Action: BaseAction
{
Protected override ChangeID(int value)
{
//Do whatever you want
}
public Action()
{
ActionStatement(RetrieveData);
}
}

If you just do:
public abstract class BaseAction
{
protected void Foo()
{
Console.WriteLine(this.GetType());
}
}
public class Action : BaseAction
{
public void Bar()
{
Foo();
}
}
// the runtime type of foo will be Action regardless of compile-time type
BaseAction foo = new Action();
foo.Bar();
it will output Action - that is, in an inherited method (Foo()) the object this will already be of the inheriting type Action if the method was ultimately called through an object of runtime type Action.
(Ignoring for now things like the new modifier on methods or explicit interface implementation.)

Related

C# How to call a derived methods?

I have a situation where I want to call only one method and have all the methods its derived from called also.
public class Base
{
public virtual void Method()
{
// Do something
}
}
public class Derived1 : Base
{
public override void Method()
{
base.Method();
// Do something
}
}
public class Derived2 : Derived1
{
public override void Method()
{
base.Method();
// Do something
}
}
I want to only call Derived2.Method() and have all the Methods() called that it derives from
The issue with the way I currently have it set up is that Derived1.Method() never gets called.
Is there a way to make the called method call all the previous instances of it in a derived class?

Override method from instance of the class

I have a merly simple question, but seems cant find an answer for it, I want to know if its possible to override a method from a instance class structore would look like this:
public class A : baseA
{
public virtual void methodA()
{
}
}
public class B : baseB
{
public void method B()
{
var ClassA = new A();
}
/* Now Is there some sort of overide like */
public override methodA()
{
//Do stuff
}
}
And those classes do not inherit from each other, to make it more difficult.
Now if this sort of construction is possible in c#?
No. You cannot override a class's behavior if you don't inherit from it.
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
Class B must inherit from class A in order to do so.
public class A
{
public virtual void methodA()
{
}
}
public class B : A
{
public void methodB()
{
var ClassA = new A();
}
public override void methodA()
{
//Do stuff
}
}
Check MSDN for more details:
An override method provides a new implementation of a member that is inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method

Define base class constructor methods in derived classes

I am trying to create a comprehensive abstract BaseClass that defines the way in which all derived classes are created, but allows derived classes to specialize/aggregate the fields and methods used in the creation process. Here is a simplified example:
public abstract class BaseClass
{
public List<String> list;
public BaseClass()
{
defineList();
optionalDoSomething();
doSomething();
}
protected void defineList()
{
list = new List<String>();
}
protected void doSomething()
{
// do something w/ list here
}
protected void optionalDoSomething() {}
}
public class DerivedClass : BaseClass
{
protected void defineList()
{
base.defineList();
list.Add("something");
}
public DerivedClass() : base() { }
}
public class SecondDerivedClass : DerivedClass
{
protected void defineList()
{
base.defineList();
list.Add("somethingElse");
}
protected void optionalDoSomething()
{
// do something special
}
public SecondDerivedClass() : base() { }
}
This would free all derived classes from having to recreate the same initialization logic, and each derived class would only need to "overwrite" the necessary fields and methods used in the create process (and possibly elsewhere in the class).
The problem:
I cannot mark BaseClass' methods as virtual since you cannot call virtual methods in a base constructor (in any case, I would not want to use virtual methods since, for example, I would not want DerivedClass to use SecondDerivedClass' defineList method).
I can mark them abstract, but then I would not be able to put "default implementations" in BaseClass and each derived class would have to replicate/implement those defaults. Also, SecondDerived class would still need a way to "override" the implementations of DerivedClass.
It does not work to simply use the new key word "hide" less derived class' methods.
What is the correct way to obtain this pattern?
TLDR: as per my comment below:
If BaseClass is an abstract class with method A, and DerivedClass is a class derived from BaseClass (not necessarily a direct child of BaseClass), then calling A in BaseClass' constructor should call A() in every class in the inheritance hierarchy up to and including DerivedClass (but no further). We can assume that A (forced to be) defined on every intermediate class.
I think that you should refer to template-method-design-pattern
Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine certain
steps of an algorithm without changing the algorithm's structure.
you can try something similar to this
abstract class AbstractClass
{
public List<String> list;
public abstract void PrimitiveOperation1();
public void TemplateMethod()
{
//initialize code that each class should perform
PrimitiveOperation1();
}
}
class DerivedClass: AbstractClass
{
public override void PrimitiveOperation1()
{
list.Add("something");
}
}
usage
AbstractClass abstractClass1 = new DerivedClass();
abstractClass1.TemplateMethod();
Try this solution, the implementation is implemented with protected virtual methods, so its not visible from the outside and not required in derived classes:
public abstract class BaseClass
{
public List<String> List { get; protected set; }
protected BaseClass()
{
defineList();
optionalDoSomething();
doSomething();
}
protected void defineList()
{
// default implementation here
List = new List<String>();
internalDefineList();
}
protected void doSomething()
{
// default implementation here
internalDoSomething();
}
protected void optionalDoSomething()
{
// default implementation here
internalOptionalSomething();
}
protected virtual void internalDefineList()
{
}
protected virtual void internalDoSomething()
{
}
protected virtual void internalOptionalSomething()
{
}
}
public class DerivedClass : BaseClass
{
protected override void internalDefineList()
{
var list = List;
}
protected override void internalDoSomething()
{
}
// this method is not required
/*
protected override void internalOptionalSomething()
{
}
*/
}
One way to achieve what you want is to add an explicit Initialize method to the base class and do the initializaiton logic there, e.g:
public abstract class BaseClass
{
public List<String> list;
public BaseClass()
{
}
public void Initialize()
{
defineList();
optionalDoSomething();
doSomething();
}
}

Why do we use virtual and override?

Why do we use override and virtual if it gives the same effect when we dont use override and virtual?
example 1:
class BaseClass
{
public virtual string call()
{
return "A";
}
}
class DerivedClass : BaseClass
{
public override string call()
{
return "B";
}
}
output : B
Example 2:
class BaseClass
{
public string call()
{
return "A";
}
}
class DerivedClass : BaseClass
{
public string call()
{
return "B";
}
}
and the output is still the same:
output : B
to run the test:
class Program
{
static void Main(string[] args)
{
DerivedClass dc = new DerivedClass();
Console.WriteLine(dc.call());
Console.ReadKey();
}
}
Does the compiler add virtual and override automatically at compile time?
I would be pleased if someone would explain to me the reason for using virtual and override.
(note, I'm quietly ignoring the compile errors)
Now do:
BaseClass obj = new DerivedClass();
Console.WriteLine(obj.call());
Without virtual, this will print A, when actually a DerivedClass should be writing B. This is because it has simply called the BaseClass implementation (since obj is typed as BaseClass, and no polymorphism is defined).
Virtual and override are a base mechanism of inheritance in object oriented programming.
This is perhaps the most important thing to understand when you use classes in a language like C# or Java.
http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
Inheritance allow you to reuse code adding new fields, properties and methods or replacing methods and properties of previously defined classes.
Virtual and Override allow you to replace the content of a method, and when i say replace, i say replace.
I would propose you a nice example.
public class MyClassEnglish
{
public virtual string SomethingToSay()
{
return "Hello!";
}
public void WriteToConsole()
{
Console.WriteLine(this.SomethingToSay());
}
}
public class MyClassItalian :
MyClassEnglish
{
public override string SomethingToSay()
{
return "Ciao!";
}
}
int main()
{
MyClassItalian it = new MyClassItalian();
it.WriteToConsole();
}
If you omit virtual and override, MyClassItalian will print out "Hello!" and not "Ciao!".
In your example you show a Shadowing technique, but the compiler should give you a warning.
You shoul add the "new" keyword if you want to hide a method in a base class.
Hiding a method is not overriding! Is just hiding.
One possible use that comes into my mind is that it can be used when you need some kind of optimization for example.
public abstract class MySpecialListBase
{
public int Count()
{
return this.GetCount();
}
protected abstract int GetCount();
}
public sealed class MySpecialArrayList : MySpecialListBase
{
int count;
public new int Count()
{
return this.count;
}
protected override int GetCount()
{
return this.count;
}
}
Now...
You can use MySpecialListBase in all your code, and when you call the Count() it will call the virtual method GetCount().
But if you use just MySpecialArrayList it will call the optimized Count() that is not virtual and that just return a field, increasing performances.
// This works with all kind of lists, but since it is a more general purpose method it will call the virtual method.
public void MyMethod(MySpecialListBase list)
{
Console.WriteLine(list.Count());
}
// This works only with MySpecialArrayList, and will use the optimized method.
public void MyMethod(MySpecialArrayList list)
{
Console.WriteLine(list.Count());
}
Best example I can think of where this is useful is when you create your own object(class) and you have to add a list of that object to a combobox.
When you add your object to the combobox you want to be able to control what text is displayed for each item. Object.toString is a virtual method. http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx and because of this you can override that method and set .toString to display the correct information about your object by overriding it.
public MyClass()
{
private int ID;
public override string ToString()
{
return "My Item:" + ID;
}
}
Method Overriding:
Where you define or implement a virtual method in a parent class and then replace it in a descendant class.
When you decide to declare a method as virtual, you are giving permission to derived classes to extend and override the method with their own implementation. You can have the extended method call the parent method's code too.
In most OO languages you can also choose to hide a parent method. When you introduce a new implementation of the same named method with the same signature without overriding, you are hiding the parent method.
C# Overriding
In C#, you specify a virtual method with the virtual keyword in a parent class and extend (or replace) it in a descendant class using the override keyword.
Use the base keyword in the descendant method to execute the code in the parent method, i.e. base.SomeMethod().
Syntax Example:
class Robot
{
public virtual void Speak()
{
}
}
class Cyborg:Robot
{
public override void Speak()
{
}
}
Override Details
You cannot override a regular non-virtual method, nor a static method.
The first version of the parent method must be virtual or abstract.
You can override any parent method marked virtual, abstract, or override (already overridden).
The methods must have the same signature.
The methods must have the same visibility (the same access level).
Use the base keyword to refer to the parent class as in base.SomeMethod().
C# Override Example
The following code snippet demonstrates using virtual and override to override a parent method in a descendant class.
using System;
class Dog
{
public virtual void Bark()
{
Console.WriteLine("RUFF!");
}
}
class GermanShepard:Dog
{
public override void Bark()
{
Console.WriteLine("Rrrrooouuff!!");
}
}
class Chiuaua:Dog
{
public override void Bark()
{
Console.WriteLine("ruff");
}
}
class InclusionExample
{
public static void Main()
{
Dog MyDog=new Dog();
MyDog=new GermanShepard();
MyDog.Bark(); // prints Rrrrooouuff!!
MyDog=new Chiuaua();
MyDog.Bark(); // prints ruff;
}
}
Hiding a Method with New
Use the new keyword to introduce a new implementation of a parent method (this hides the parent method). You can hide a method without using new but you will get a compiler warning. Using new will suppress the warning.
The new and override modifiers have different meanings. The new modifier creates a new member with the same name, signature, and visibility and hides the original member. The override modifier extends the implementation for an inherited member and allows you to implement inheritance-based polymorphism.
Avoid Introducing New Members: Sometimes there are clear reasons to introduce a new method with the same name, signature, and visibility of a parent method. In those clear cases, introducing a new member is a powerful feature. However, if you do not have a clear reason, then avoid introducing a new version of a method by naming the new method something unique and appropriate.
class Robot : System.Object
{
public void Speak()
{
MessageBox.Show("Robot says hi");
}
}
class Cyborg : Robot
{
new public void Speak()
{
MessageBox.Show("hi");
}
}
Calling the Base Class Version
A common task In OO is to extend a method by first executing the parent method code and then adding code. Use the base keyword to refer to the parent class as in base.SomeMethod().
class Robot : System.Object
{
public virtual void Speak()
{
MessageBox.Show("Robot says hi");
}
}
class Cyborg : Robot
{
public override void Speak()
{
base.Speak();
MessageBox.Show("hi");
}
}

Call base function then inherited function

I have a base class and a class inheriting base. The base class has several virtual functions that the inherited class may override. However, the virtual functions in the base class has code that MUST to run before the inherited class overrides get called. Is there some way that I can call the base classes virtual functions first then the inherited class overrides. Without making a call to base.function().
I know I can simply make two functions, one that gets called, the other virtual. But is there a way I can keep the same names as well? I know I may need to change some things around.
class myBase
{
public virtual myFunction()
{ /* must-run code, Called first */ }
}
class myInherited : myBase
{
public override myFunction()
{ /* don't use base.myFunction();,
called from base.myFunction(); */ }
}
Similar question here.
C# doesn't have support for automatically enforcing this, but
you can enforce it by using the template method pattern. For example, imagine you had this code:
abstract class Animal
{
public virtual void Speak()
{
Console.WriteLine("I'm an animal.");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak();
Console.WriteLine("I'm a dog.");
}
}
The trouble here is that any class inheriting from Animal needs to call base.Speak(); to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:
abstract class Animal
{
public void Speak()
{
Console.WriteLine("I'm an animal.");
DoSpeak();
}
protected abstract void DoSpeak();
}
class Dog : Animal
{
protected override void DoSpeak()
{
Console.WriteLine("I'm a dog.");
}
}
In this case, clients still only see the polymorphic Speak method, but the Animal.Speak behavior is guaranteed to execute. The problem is that if you have further inheritance (e.g. class Dachshund : Dog), you have to create yet another abstract method if you want Dog.Speak to be guaranteed to execute.
A common solution that can be found in the .NET Framework is to split a method in a public method XXX and a protected, virtual method OnXXX that is called by the public method. For your example, it would look like this:
class MyBase
{
public void MyMethod()
{
// do something
OnMyMethod();
// do something
}
protected virtual void OnMyMethod()
{
}
}
and
class MyInherited : MyBase
{
protected override void OnMyMethod()
{
// do something
}
}
public abstract class BaseTemp
{
public void printBase() {
Console.WriteLine("base");
print();
}
public abstract void print();
}
public class TempA: BaseTemp
{
public override void print()
{
Console.WriteLine("TempA");
}
}
public class TempB: BaseTemp
{
public override void print()
{
Console.WriteLine("TempB");
}
}
There is no way to do what you're seeking other than the 2 ways you already named.
Either you make 2 functions in the base class, one that gets called and the other virtual.
Or you call base.functionName in the sub-class.
Not exactly. But I've done something similar using abstract methods.
Abstract methods must be overriden by derived classes. Abstract procs are virtual so you can be sure that when the base class calls them the derived class's version is called. Then have your base class's "Must Run Code" call the abstract proc after running. voila, your base class's code always runs first (make sure the base class proc is no longer virtual) followed by your derived class's code.
class myBase
{
public /* virtual */ myFunction() // remove virtual as we always want base class's function called here
{ /* must-run code, Called first */
// call derived object's code
myDerivedMustcallFunction();
}
public abstract myDerivedMustCallFunction() { /* abstract functions are blank */ }
}
class myInherited : myBase
{
public override myDerivedMustCallFunction()
{ /* code to be run in derived class here */ }
}
What do you think of this?
class myBase
{
public void myFunctionWrapper()
{
// do stuff that must happen first
// then call overridden function
this.myFunction();
}
public virtual void myFunction(){
// default implementation that can be overriden
}
}
class myInherited : myBase
{
public override void myFunction()
{
}
}

Categories

Resources