C# : calling base method from overridden one - c#

With those classes:
public abstract class T_BaseClass
{
public virtual void m_canvas()
{
Console.WriteLine("canvas method called from template.");
}
}
public class C_ChildT : T_BaseClass
{
public override void m_canvas()
{
base.m_canvas();
Console.WriteLine("canvas method called from child template.");
}
}
What is the differences between those two implementations?
Difference between
C_ChildT mychildclass = new C_ChildT();
and
T_BaseClass mychildclass1 = new C_ChildT();
mychildclass.m_canvas();
mychildclass1.m_canvas();
Hope it looks better M.Skeet.
Thank you for your answer.

Basically, you don't need a deep understanding of inheritance to work with it. The minimum, that you should know is that the last child of inheritance sequence methods is called, when you call any method on an object. Also you should know that variable type and object type are different things, and you can store an object of child types in a variable of parent type. So, in your example you have two variables with C_ChildT and T_BaseClass types. But both objects are C_ChildT type. So when you call m_canvas() on each of them, you will call the C_ChildT implementation of m_canvas() in both cases.
Under the hood, when you call a virtual method, your runtime evironment sees, that the method is marked with the virtual keyword, so it (runtime environment) starts looking for overrriding of this method in the most derived class. You can read more about it here.

Related

Are instance methods duplicated in memory for each object?

To be more clear about my question, if you create an array of a particular class: for example,
ExampleClass[] test = new ExampleClass[5];
I know the five ExampleClass instances would create a copy of each variable for each class, but are the methods/functions duplicated 5 times in memory, or do each of the tests just point to the same single class codebase? If it duplicated for each class, that would just be a waste of memory.
Every type loaded into an AppDomain will have a Method Table structure that holds every method that type defines, plus the virtual methods derived from parent (typically Object) and the methods defined by any implemented interface.
This Method Table is pointed by every instance of that object. So every instance does not duplicate all the methods defined by that type, but points to this method table structure with a reference.
For example:
public class MyClass : IDisposable
{
private static void MyStaticMethod()
{
// ....
}
public void MyInstanceMethod()
{
// ....
}
public void Dispose()
{
throw new NotImplementedException();
}
}
This MyClass will have a method table including:
MyStaticMethod
MyInstanceMethod
Dispose
And other virtual methods derived from System.Object
Have a look at nice diagram of method table:
You can check the whole article about method tables here

Why do I need to declare a Virtual Method when I can Hide it in derived Class

class clsTestParent
{
public void testNoAbstract()
{
Console.WriteLine("Parent Method Call");
}
}
class clsDerivedTest : clsTestParent
{
public void testNoAbstract()
{
Console.WriteLine("Child Method Hiding Parent Method");
}
}
clsTestParent objParent = new clsTestParent();
clsTestParent objOfParentFromDerived = new clsDerivedTest();
clsDerivedTest objDerived = new clsDerivedTest();
objParent.testNoAbstract();
objOfParentFromDerived.testNoAbstract();
objDerived.testNoAbstract();
Output:
Parent Method Call
Parent Method Call
Child Method Hiding Parent Method
But when I declare testNoAbstract() as virtual and over ride in derived class , then the out put will be as below:
Parent Method Call
Child Method Hiding Parent Method
Child Method Hiding Parent Method
Earlier I used to think , we can only redefine a method in derived class , if that is defined as abstract or virtual , but as can see now , we can hide the parent class method just by redefining it in derived class.
Though , I can see , the difference in output by changing the code , I would like to know , What are the differences between above two methods and why it yields different out put.
If youll ever do clsTestParent a = new clsDerivedTest () - you'll never be able to execute the one in the clsDerivedTest class !!!!
Thats the difference and thats why the compiler warns you.
you'll actually gonna do that if you wish to preform a Polymorphism architecture.
Microsoft tells you : " listen , you direved a class , and we will give you all the public things etc but we dont know how do you want to implement the methods ... if you'll use the virtual + override - youll be able to execute a different method via the instace type. and if you wont override - so the function of the father will always be executed.... its your choice ... we are warning you "... and they do warn
This is why 'redefinition' is somewhat bad word for that. Virtual call resolves your type runtime, that's why you were able to:
clsTestParent objOfParentFromDerived = new clsDerivedTest();
objOfParentFromDerived.testAbstractOrVirtual(); // marked as virtual or abstract in base class
and the call was resolved in runtime, to the method defined in a class that objOfParentFromDerived really is (new operator - clsDerivedTest), and not to the method defined in a class it was declared with(clsTestParent).
If it's not marked neither virtual or abstract then the compiler warns you, because the call will be resolved basing on the type the variable has been declared with.

How can I call MemberwiseClone()?

I'm confused about how to use the MemberwiseClone() method. I looked the example in MSDN and they use it trough the this keyword.
Why I can not call it directly as other objects' methods like GetType() or ToString()? Another related method that does not appear is ShallowCopy().
If they are part of the Object class why can't I see them?
The MemberwiseClone() function is protected, so you can only access it through a qualifier of your own type.
Here is an example, this is what I did and no problems so far.
public class ModelBase
{
public T ShallowCopy<T>() where T : ModelBase
{
return (T)(MemberwiseClone());
}
}
And call it like:
var cloned = User.ShallowCopy<User>();

How can I make a delegate refer to a specific version of a method?

I'd like to make a delegate that invokes a specific instance method, unfortunately, it seems that if the method is virtual, the override of the method for the inheriting class will be invoked rather than the base version.
public class Base{
public virtual void Method(){
Console.WriteLine("Base");
}
}
public class Child : Base{
public override void Method(){
Console.WriteLine("Child");
}
}
If somewhere else in the code I have the following::
var action = Delegate.CreateDelegate(typeof(Action<Base>), typeof(Base).GetMethod("Method")) as Action<Base>;
action(new Child());
The output of this program is Child. I'd really like it to be Base. I've tried the same thing with expression trees and I get the same result, as the IL emitted uses the callvirt method. Is the only way to do something like this really with Reflection.Emit?
The reason I ask is that I am using a type builder to override behavior of a class. If I were to write the method myself, I could just go base.Method() or whatever, but, some of the method behavior can only be determined dynamically at runtime, as accounting for the many possible cases would be very tedious.
Since i'm creating a class that derives from Base at runtime, if I try to invoke Method() inside the Method() overload I'm making it leads to infinite recursion and stack overflow exceptions. (not so good).
This is for an AOP style project where I'm adding some logic to the methods at runtime. I tag the methods with attributes, I then have a type builder that create methodBuilders feeding the body of the methodbuilder with an expression tree using the CompileToMethod(methodbuilder) http://msdn.microsoft.com/en-us/library/dd728224.aspx,
This is a ton easier than reflection.emit, as the logic is non-trivial that I am adding. The goal is than I have a factory spit out a new class that whenever I call Method() it does some logic first before ultimately calling the base implementation.
Yes, Reflection.Emit is the only way provided by the .NET framework to implement method overloads. Since the other APIs aren't used when overloading methods, they don't provide any way to chain to the base implementation.
Maybe you can use such a workaround:
public class Base{
public virtual void Method(){
MethodImpl();
}
public void MethodImpl(){
Console.WriteLine("Base");
}
}
public class Child : Base{
public override void Method(){
Console.WriteLine("Child");
}
}
Now, you can create a delegate representing MethodImpl.
What's suppose to happen here?
class Base { public abstract void Method(); }
class Child {
public override void Method() {
Console.WriteLine("Child.Method");
}
}
Action<Base> magicalAction = // defined somehow
magicalAction(new Child()); // aiya!
You're trying to defeat the point of virtual methods. Why?
Since Reflection.Emit is such a difficult way to build a whole method, I would recommend using Reflection.Emit to create private methods just for calling the base methods. Then you can refer to those methods from your Expressions.

C# virtual static method

Why is static virtual impossible? Is C# dependent or just don't have any sense in the OO world?
I know the concept has already been underlined but I did not find a simple answer to the previous question.
virtual means the method called will be chosen at run-time, depending on the dynamic type of the object. static means no object is necessary to call the method.
How do you propose to do both in the same method?
Eric Lippert has a blog post about this, and as usual with his posts, he covers the subject in great depth:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/calling-static-methods-on-type-parameters-is-illegal-part-one
“virtual” and “static” are opposites! “virtual” means “determine the method to be called based on run time type information”, and “static” means “determine the method to be called solely based on compile time static analysis”
The contradiction between "static" and "virtual" is only a C# problem. If "static" were replaced by "class level", like in many other languages, no one would be blindfolded.
Too bad the choice of words made C# crippled in this respect. It is still possible to call the Type.InvokeMember method to simulate a call to a class level, virtual method. You just have to pass the method name as a string. No compile time check, no strong typing and no control that subclasses implement the method.
Some Delphi beauty:
type
TFormClass = class of TForm;
var
formClass: TFormClass;
myForm: TForm;
begin
...
formClass = GetAnyFormClassYouWouldLike;
myForm = formClass.Create(nil);
myForm.Show;
end
Guys who say that there is no sense in static virtual methods - if you don't understand how this could be possible, it does not mean that it is impossible. There are languages that allow this!! Look at Delphi, for example.
I'm going to be the one who naysays. What you are describing is not technically part of the language. Sorry. But it is possible to simulate it within the language.
Let's consider what you're asking for - you want a collection of methods that aren't attached to any particular object that can all be easily callable and replaceable at run time or compile time.
To me that sounds like what you really want is a singleton object with delegated methods.
Let's put together an example:
public interface ICurrencyWriter {
string Write(int i);
string Write(float f);
}
public class DelegatedCurrencyWriter : ICurrencyWriter {
public DelegatedCurrencyWriter()
{
IntWriter = i => i.ToString();
FloatWriter = f => f.ToString();
}
public string Write(int i) { return IntWriter(i); }
public string Write(float f) { return FloatWriter(f); }
public Func<int, string> IntWriter { get; set; }
public Func<float, string> FloatWriter { get; set; }
}
public class SingletonCurrencyWriter {
public static DelegatedCurrencyWriter Writer {
get {
if (_writer == null)
_writer = new DelegatedCurrencyWriter();
return _writer;
}
}
}
in use:
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400.0
SingletonCurrencyWriter.Writer.FloatWriter = f => String.Format("{0} bucks and {1} little pennies.", (int)f, (int)(f * 100));
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400 bucks and 0 little pennies
Given all this, we now have a singleton class that writes out currency values and I can change the behavior of it. I've basically defined the behavior convention at compile time and can now change the behavior at either compile time (in the constructor) or run time, which is, I believe the effect you're trying to get. If you want inheritance of behavior, you can do that to by implementing back chaining (ie, have the new method call the previous one).
That said, I don't especially recommend the example code above. For one, it isn't thread safe and there really isn't a lot in place to keep life sane. Global dependence on this kind of structure means global instability. This is one of the many ways that changeable behavior was implemented in the dim dark days of C: structs of function pointers, and in this case a single global struct.
Yes it is possible.
The most wanted use case for that is to have factories which can be "overriden"
In order to do this, you will have to rely on generic type parameters using the F-bounded polymorphism.
Example 1
Let's take a factory example:
class A: { public static A Create(int number) { return ... ;} }
class B: A { /* How to override the static Create method to return B? */}
You also want createB to be accessible and returning B objects in the B class. Or you might like A's static functions to be a library that should be extensible by B. Solution:
class A<T> where T: A<T> { public static T Create(int number) { return ...; } }
class B: A<B> { /* no create function */ }
B theb = B.Create(2); // Perfectly fine.
A thea = A.Create(0); // Here as well
Example 2 (advanced):
Let's define a static function to multiply matrices of values.
public abstract class Value<T> where T : Value<T> {
//This method is static but by subclassing T we can use virtual methods.
public static Matrix<T> MultiplyMatrix(Matrix<T> m1, Matrix<T> m2) {
return // Code to multiply two matrices using add and multiply;
}
public abstract T multiply(T other);
public abstract T add(T other);
public abstract T opposed();
public T minus(T other) {
return this.add(other.opposed());
}
}
// Abstract override
public abstract class Number<T> : Value<T> where T: Number<T> {
protected double real;
/// Note: The use of MultiplyMatrix returns a Matrix of Number here.
public Matrix<T> timesVector(List<T> vector) {
return MultiplyMatrix(new Matrix<T>() {this as T}, new Matrix<T>(vector));
}
}
public class ComplexNumber : Number<ComplexNumber> {
protected double imag;
/// Note: The use of MultiplyMatrix returns a Matrix of ComplexNumber here.
}
Now you can also use the static MultiplyMatrix method to return a matrix of complex numbers directly from ComplexNumber
Matrix<ComplexNumber> result = ComplexNumber.MultiplyMatrix(matrix1, matrix2);
While technically it's not possible to define a static virtual method, for all the reasons already pointed out here, you can functionally accomplish what I think you're trying using C# extension methods.
From Microsoft Docs:
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Check out Extension Methods (C# Programming Guide) for more details.
In .NET, virtual method dispatch is (roughly) done by looking at the actual type of an object when the method is called at runtime, and finding the most overriding method from the class's vtable. When calling on a static class, there is no object instance to check, and so no vtable to do the lookup on.
To summarize all the options presented:
This is not a part of C# because in it, static means "not bound to anything at runtime" as it has ever since C (and maybe earlier). static entities are bound to the declaring type (thus are able to access its other static entities), but only at compile time.
This is possible in other languages where a static equivalent (if needed at all) means "bound to a type object at runtime" instead. Examples include Delphi, Python, PHP.
This can be emulated in a number of ways which can be classified as:
Use runtime binding
Static methods with a singleton object or lookalike
Virtual method that returns the same for all instances
Redefined in a derived type to return a different result (constant or derived from static members of the redefining type)
Retrieves the type object from the instance
Use compile-time binding
Use a template that modifies the code for each derived type to access the same-named entities of that type, e.g. with the CRTP
The 2022+ answer, if you are running .Net 7 or above, is that now static virtual members is now supported in interfaces. Technically it's static abstract instead of "static virtual" but the effect is that same. Standard static methods signatures can be defined in an interface and implemented statically.
Here are a few examples on the usage and syntax in .Net 7

Categories