MyClass equivalent in C# - c#

In looking at this question, commenter #Jon Egerton mentioned that MyClass was a keyword in VB.Net. Having never used it, I went and found the documentation on it:
The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented. MyClass is similar to Me, but all method calls on it are treated as if the method were NotOverridable.
I can see how that could kind of be useful, in some specific scenarios. What I can't think of is, how would you obtain the same behaviour in C# - that is, to ensure that a call to a virtual method myMethod is actually invoked against myMethod in the current class, and not a derived myMethod (a.k.a in the IL, invoking call rather than callvirt)?
I might just be having a complete mental blank moment though.

According to Jon Skeet, there is no such equivalent:
No, C# doesn't have an equivalent of VB.NET's MyClass keyword. If you want to guarantee not to call an overridden version of a method, you need to make it non-virtual in the first place.
An obvious workaround would be this:
public virtual void MyMethod()
{
MyLocalMethod();
}
private void MyLocalMethod()
{
...
}
Then you could call MyLocalMethod() when a VB user would write MyClass.MyMethod().

There is no C# equivalent of the MyClass keyword in VB.Net. To guarantee that an overridden version of a method will not be called, simply make it non-virtual.

In addition to answers saying it doesn't exist, so you have to make it non-virtual.
Here's a smelly (read: don't do this!) work-around. But seriously, re-think your design.
Basically move any method that must have the base one called into 'super'-base class, which sits above your existing base class. In your existing class call base.Method() to always call the non-overridden one.
void Main()
{
DerivedClass Instance = new DerivedClass();
Instance.MethodCaller();
}
class InternalBaseClass
{
public InternalBaseClass()
{
}
public virtual void Method()
{
Console.WriteLine("BASE METHOD");
}
}
class BaseClass : InternalBaseClass
{
public BaseClass()
{
}
public void MethodCaller()
{
base.Method();
}
}
class DerivedClass : BaseClass
{
public DerivedClass()
{
}
public override void Method()
{
Console.WriteLine("DERIVED METHOD");
}
}

Related

Can a delegate created for a base class method actually call a derived class method?

I have the following code:
using System;
using static System.Console;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Test.StartTest();
ReadLine();
}
}
public class Test
{
class SomeResult {}
class BaseClass
{
public virtual TResult DoSomething<TResult>()
{
WriteLine(nameof(BaseClass));
return default;
}
}
class DerivedClass : BaseClass
{
public override TResult DoSomething<TResult>()
{
WriteLine(nameof(DerivedClass));
Func<TResult> baseImplementation = base.DoSomething<TResult>;
//This works: return base.DoSomething<TResult>();
return baseImplementation();
}
}
public static void StartTest()
{
DerivedClass instance = new DerivedClass();
instance.DoSomething<SomeResult>();
//This works: instance.DoSomething<int>();
WriteLine("Finished");
}
}
}
Basically, I have BaseClass and DerivedClass (which derives from BaseClass) inside the class Test (I don't think it's important that the former classes are inside Test, but I'll leave it like that in case I'm missing something).
BaseClass has the virtual method DoSomething, which DerivedClass overrides to call the base class implementation, but doing so by creating a Func delegate "pointing" to BaseClass.DoSomething, and calling that delegate (take into account this is just a barebones example and not exactly what I was trying to accomplish in a real project).
When running the program an instance of DerivedClass is created, and its DoSomething method is called, which should call BaseClass.DoSomething via the delegate as mentioned before. When I run it in Visual Studio it works as I would expect it to, BaseClass.DoSomething is indeed called (the output is "DerivedClass BaseClass Finished"). However, when running it elsewhere (the Unity game engine, but it's not relevant) the delegate does not call BaseClass.DoSomething, but DerivedClass.DoSomething (entering a loop and causing a stack overflow exception). It doesn't happen with the lines commented out with "//This works:", even though I'd assume them to be mostly equivalent.
Wouldn't the expected behaviour be that calling the delegate always executes BaseClass.DoSomething, or am I missing something and it's an implementation detail and not a well-defined rule in the language? My first assumption is that it's a bug in either Unity or the version of Mono that it uses, but I'm not sure if there's something else I have to consider.
The behaviour must be that the delegate executes the base class method, not the derived class method. I received confirmation from Unity that the backwards behaviour is indeed a bug.

What type does the 'this' keyword actually refer to?

I have the following code
public class Base {
public Base() {}
public virtual void IdentifyYourself() {
Debug.Log("I am a base");
}
public void Identify() { this.IdentifyYourself(); }
}
public class Derived : Base {
public Derived() {}
public override void IdentifyYourself() {
Debug.Log("I am a derived");
}
}
I run the following test code in a different entrypoint:
Base investigateThis = new Derived();
investigateThis.Identify()
and the output is: "I am a derived"
So no matter where the C# 'this' keyword is used; does it always refer to the run-time type no matter what scope 'this' is used in?
Bonus points to anyone who was able to 'Google' better than me and find MSDN documentation on specifically 'this' (pun intended) behavior.
Lastly, does anyone happen to know what is happening under the hood? Is it just a cast?
Update #1: Fixed typo in code; With the current set of answers, I guess I did not fully understand the implications of what the MSDN documentation meant by "..is the current instance..".
Update #2: Apologies, I wasn't sure if I should have made a separate question, but on further investigation, I've confused myself again; given this updated code, why is the output both: "I am a derived" & "It is a base!".
Didn't other people answer that 'this' is indeed the run-time type? Let me know if my updated question still is not clear.
Updated code:
public class Base {
public Base() {}
public virtual void IdentifyYourself() {
Debug.Log("I am a base");
}
//Updated the code here...
public void Identify() { this.IdentifyYourself(); AnotherTake(); }
public void AnotherTake() { WhatIsItExactly(this); }
public void WhatIsItExactly(Derived thing) {
Debug.Log("It is a derived!");
}
public void WhatIsItExactly(Base thing) {
Debug.Log("It is a base!");
}
}
public class Derived : Base {
public Derived() {}
public override void IdentifyYourself() {
Debug.Log("I am a derived");
}
}
Absolutely! investigateThis refers to an instance of Derived.
So the virtual method IdentifyYourself in Derived will be called. This is run-time polymorphism in effect.
The scope does not matter.
Under the hood, an virtual function table is built, and there is a pointer in the object that points to that table.
if you google: c# this the following link is the first result returned.
https://msdn.microsoft.com/en-us/library/dk1507sz.aspx
The this keyword refers to the current instance of the class and is
also used as a modifier of the first parameter of an extension method.
You may also want to take a look at base while you are at it.
https://msdn.microsoft.com/en-us/library/hfw7t1ce.aspx
The base keyword is used to access members of the base class from
within a derived class:
Call a method on the base class that has been overridden by another
method.
Specify which base-class constructor should be called when creating
instances of the derived class.
'this' always refers to the current instance, whereas 'base' always refers to the inherited type, regardless of whether the code using 'this' is in the base or the child class, it will always refer to the child (unless the base is instantiated itself, of course). It's just a reference to the current instance, like 'self' in python. Useful if a parameter has the same name as a private field, but as far as I'm aware it has no functional purpose other than that, I use it for readability, to clearly show when something belongs to the class I'm working in.

Overriding vs method hiding [duplicate]

This question already has answers here:
Difference between shadowing and overriding in C#?
(7 answers)
Closed 3 years ago.
I am a bit confused about overriding vs. hiding a method in C#. Practical uses of each would also be appreciated, as well as an explanation for when one would use each.
I am confused about overriding - why do we override? What I have learnt so far is that by overring we can provide desired implementation to a method of a derived class, without changing the signature.
If I don't override the method of the superclass and I make changes to the method in the sub class, will that make changes to the super class method ?
I am also confused about the following - what does this demonstrate?
class A
{
virtual m1()
{
console.writeline("Bye to all");
}
}
class B : A
{
override m1()
{
console.writeLine("Hi to all");
}
}
class C
{
A a = new A();
B b = new B();
a = b; (what is this)
a.m1(); // what this will print and why?
b = a; // what happens here?
}
Consider:
public class BaseClass
{
public void WriteNum()
{
Console.WriteLine(12);
}
public virtual void WriteStr()
{
Console.WriteLine("abc");
}
}
public class DerivedClass : BaseClass
{
public new void WriteNum()
{
Console.WriteLine(42);
}
public override void WriteStr()
{
Console.WriteLine("xyz");
}
}
/* ... */
BaseClass isReallyBase = new BaseClass();
BaseClass isReallyDerived = new DerivedClass();
DerivedClass isClearlyDerived = new DerivedClass();
isReallyBase.WriteNum(); // writes 12
isReallyBase.WriteStr(); // writes abc
isReallyDerived.WriteNum(); // writes 12
isReallyDerived.WriteStr(); // writes xyz
isClearlyDerived.WriteNum(); // writes 42
isClearlyDerived.writeStr(); // writes xyz
Overriding is the classic OO way in which a derived class can have more specific behaviour than a base class (in some languages you've no choice but to do so). When a virtual method is called on an object, then the most derived version of the method is called. Hence even though we are dealing with isReallyDerived as a BaseClass then functionality defined in DerivedClass is used.
Hiding means that we have a completely different method. When we call WriteNum() on isReallyDerived then there's no way of knowing that there is a different WriteNum() on DerivedClass so it isn't called. It can only be called when we are dealing with the object as a DerivedClass.
Most of the time hiding is bad. Generally, either you should have a method as virtual if its likely to be changed in a derived class, and override it in the derived class. There are however two things it is useful for:
Forward compatibility. If DerivedClass had a DoStuff() method, and then later on BaseClass was changed to add a DoStuff() method, (remember that they may be written by different people and exist in different assemblies) then a ban on member hiding would have suddenly made DerivedClass buggy without it changing. Also, if the new DoStuff() on BaseClass was virtual, then automatically making that on DerivedClass an override of it could lead to the pre-existing method being called when it shouldn't. Hence it's good that hiding is the default (we use new to make it clear we definitely want to hide, but leaving it out hides and emits a warning on compilation).
Poor-man's covariance. Consider a Clone() method on BaseClass that returns a new BaseClass that's a copy of that created. In the override on DerivedClass this will create a DerivedClass but return it as a BaseClass, which isn't as useful. What we could do is to have a virtual protected CreateClone() that is overridden. In BaseClass we have a Clone() that returns the result of this - and all is well - in DerivedClass we hide this with a new Clone() that returns a DerivedClass. Calling Clone() on BaseClass will always return a BaseClass reference, which will be a BaseClass value or a DerivedClass value as appropriate. Calling Clone() on DerivedClass will return a DerivedClass value, which is what we'd want in that context. There are other variants of this principle, however it should be noted that they are all pretty rare.
An important thing to note with the second case, is that we've used hiding precisely to remove surprises to the calling code, as the person using DerivedClass might reasonably expect its Clone() to return a DerivedClass. The results of any of the ways it could be called are kept consistent with each other. Most cases of hiding risk introducing surprises, which is why they are generally frowned upon. This one is justified precisely because it solves the very problem that hiding often introduces.
In all, hiding is sometimes necessary, infrequently useful, but generally bad, so be very wary of it.
Overriding is when you provide a new override implementation of a method in a descendant class when that method is defined in the base class as virtual.
Hiding is when you provide a new implementation of a method in a descendant class when that method is not defined in the base class as virtual, or when your new implementation does not specify override.
Hiding is very often bad; you should generally try not to do it if you can avoid it at all. Hiding can cause unexpected things to happen, because Hidden methods are only used when called on a variable of the actual type you defined, not if using a base class reference... on the other hand, Virtual methods which are overridden will end up with the proper method version being called, even when called using the base class reference on a child class.
For instance, consider these classes:
public class BaseClass
{
public virtual void Method1() //Virtual method
{
Console.WriteLine("Running BaseClass Method1");
}
public void Method2() //Not a virtual method
{
Console.WriteLine("Running BaseClass Method2");
}
}
public class InheritedClass : BaseClass
{
public override void Method1() //Overriding the base virtual method.
{
Console.WriteLine("Running InheritedClass Method1");
}
public new void Method2() //Can't override the base method; must 'new' it.
{
Console.WriteLine("Running InheritedClass Method2");
}
}
Let's call it like this, with an instance of InheritedClass, in a matching reference:
InheritedClass inherited = new InheritedClass();
inherited.Method1();
inherited.Method2();
This returns what you should expect; both methods say they are running the InheritedClass versions.
Running InheritedClass Method1
Running InheritedClass Method2
This code creates an instance of the same, InheritedClass, but stores it in a BaseClass reference:
BaseClass baseRef = new InheritedClass();
baseRef.Method1();
baseRef.Method2();
Normally, under OOP principles, you should expect the same output as the above example. But you don't get the same output:
Running InheritedClass Method1
Running BaseClass Method2
When you wrote the InheritedClass code, you may have wanted all calls to Method2() to run the code you wrote in it. Normally, this would be how it works - assuming you are working with a virtual method that you have overridden. But because you are using a new/hidden method, it calls the version on the reference you are using, instead.
If that's the behavior you truly want, then; there you go. But I would strongly suggest that if that's what you want, there may be a larger architectural issue with the code.
Method Overriding is simpley override a default implementation of a base class method in the derived class.
Method Hiding : You can make use of 'new' keyword before a virtual method in a derived class
as
class Foo
{
public virtual void foo1()
{
}
}
class Bar:Foo
{
public new virtual void foo1()
{
}
}
now if you make another class Bar1 which is derived from Bar , you can override foo1 which is defind in Bar.

Force base method call

Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a compile-time error if it isn't called? That would be very convenient..
--edit--
I am mainly curious about overriding methods.
There isn't and shouldn't be anything to do that.
The closest thing I can think of off hand if something like having this in the base class:
public virtual void BeforeFoo(){}
public void Foo()
{
this.BeforeFoo();
//do some stuff
this.AfterFoo();
}
public virtual void AfterFoo(){}
And allow the inheriting class override BeforeFoo and/or AfterFoo
Not in Java. It might be possible in C#, but someone else will have to speak to that.
If I understand correctly you want this:
class A {
public void foo() {
// Do superclass stuff
}
}
class B extends A {
public void foo() {
super.foo();
// Do subclass stuff
}
}
What you can do in Java to enforce usage of the superclass foo is something like:
class A {
public final void foo() {
// Do stuff
...
// Then delegate to subclass
fooImpl();
}
protected abstract void fooImpl();
}
class B extends A {
protected void fooImpl() {
// Do subclass stuff
}
}
It's ugly, but it achieves what you want. Otherwise you'll just have to be careful to make sure you call the superclass method.
Maybe you could tinker with your design to fix the problem, rather than using a technical solution. It might not be possible but is probably worth thinking about.
EDIT: Maybe I misunderstood the question. Are you talking about only constructors or methods in general? I assumed methods in general.
The following example throws an InvalidOperationException when the base functionality is not inherited when overriding a method.
This might be useful for scenarios where the method is invoked by some internal API.
i.e. where Foo() is not designed to be invoked directly:
public abstract class ExampleBase {
private bool _baseInvoked;
internal protected virtual void Foo() {
_baseInvoked = true;
// IMPORTANT: This must always be executed!
}
internal void InvokeFoo() {
Foo();
if (!_baseInvoked)
throw new InvalidOperationException("Custom classes must invoke `base.Foo()` when method is overridden.");
}
}
Works:
public class ExampleA : ExampleBase {
protected override void Foo() {
base.Foo();
}
}
Yells:
public class ExampleB : ExampleBase {
protected override void Foo() {
}
}
I use the following technique. Notice that the Hello() method is protected, so it can't be called from outside...
public abstract class Animal
{
protected abstract void Hello();
public void SayHello()
{
//Do some mandatory thing
Console.WriteLine("something mandatory");
Hello();
Console.WriteLine();
}
}
public class Dog : Animal
{
protected override void Hello()
{
Console.WriteLine("woof");
}
}
public class Cat : Animal
{
protected override void Hello()
{
Console.WriteLine("meow");
}
}
Example usage:
static void Main(string[] args)
{
var animals = new List<Animal>()
{
new Cat(),
new Dog(),
new Dog(),
new Dog()
};
animals.ForEach(animal => animal.SayHello());
Console.ReadKey();
}
Which produces:
You may want to look at this (call super antipatern) http://en.wikipedia.org/wiki/Call_super
If I understand correctly you want to enforce that your base class behaviour is not overriden, but still be able to extend it, then I'd use the template method design pattern and in C# don't include the virtual keyword in the method definition.
No. It is not possible. If you have to have a function that does some pre or post action do something like this:
internal class Class1
{
internal virtual void SomeFunc()
{
// no guarantee this code will run
}
internal void MakeSureICanDoSomething()
{
// do pre stuff I have to do
ThisCodeMayNotRun();
// do post stuff I have to do
}
internal virtual void ThisCodeMayNotRun()
{
// this code may or may not run depending on
// the derived class
}
}
I didn't read ALL the replies here; however, I was considering the same question. After reviewing what I REALLY wanted to do, it seemed to me that if I want to FORCE the call to the base method that I should not have declared the base method virtual (override-able) in the first place.
Don't force a base call. Make the parent method do what you want, while calling an overridable (eg: abstract) protected method in its body.
Don't think there's any feasible solution built-in. I'm sure there's separate code analysis tools that can do that, though.
EDIT Misread construct as constructor. Leaving up as CW since it fits a very limited subset of the problem.
In C# you can force this behavior by defining a single constructor having at least one parameter in the base type. This removes the default constructor and forces derived types to explcitly call the specified base or they get a compilation error.
class Parent {
protected Parent(int id) {
}
}
class Child : Parent {
// Does not compile
public Child() {}
// Also does not compile
public Child(int id) { }
// Compiles
public Child() :base(42) {}
}
In java, the compiler can only enforce this in the case of Constructors.
A constructor must be called all the way up the inheritance chain .. ie if Dog extends Animal extends Thing, the constructor for Dog must call a constructor for Animal must call a constructor for Thing.
This is not the case for regular methods, where the programmer must explicitly call a super implementation if necessary.
The only way to enforce some base implementation code to be run is to split override-able code into a separate method call:
public class Super
{
public final void doIt()
{
// cannot be overridden
doItSub();
}
protected void doItSub()
{
// override this
}
}
public class Sub extends Super
{
protected void doItSub()
{
// override logic
}
}
I stumbled on to this post and didn't necessarily like any particular answer, so I figured I would provide my own ...
There is no way in C# to enforce that the base method is called. Therefore coding as such is considered an anti-pattern since a follow-up developer may not realize they must call the base method else the class will be in an incomplete or bad state.
However, I have found circumstances where this type of functionality is required and can be fulfilled accordingly. Usually the derived class needs a resource of the base class. In order to get the resource, which normally might be exposed via a property, it is instead exposed via a method. The derived class has no choice but to call the method to get the resource, therefore ensuring that the base class method is executed.
The next logical question one might ask is why not put it in the constructor instead? The reason is that it may be an order of operations issue. At the time the class is constructed, there may be some inputs still missing.
Does this get away from the question? Yes and no. Yes, it does force the derived class to call a particular base class method. No, it does not do this with the override keyword. Could this be helpful to an individual looking for an answer to this post, maybe.
I'm not preaching this as gospel, and if individuals see a downside to this approach, I would love to hear about it.
On the Android platform there is a Java annotation called 'CallSuper' that enforces the calling of the base method at compile time (although this check is quite basic). Probably the same type of mechanism can be easily implemented in Java in the same exact way. https://developer.android.com/reference/androidx/annotation/CallSuper

Polymorphism and c#

Here one more basic question asked in MS interview recently
class A {
public virtual void Method1(){}
public void Method2() {
Method1();
}
}
class B:A {
public override void Method1() { }
}
class main {
A obk = new B();
obk.Method2();
}
So which function gets called? Sorry for the typos.
B.Method1();
gets called because it properly overrides the virtual method A.Method1();
In this case B.Method1 gets called. This is because even though the variable is typed as A the actual type of the instance is B. The CLR polymorphically dispatches calls to Method1 based on the actual type of the instance, not the type of the variable.
Method1 from class B will be called, as you can see by running the below program:
class Program
{
static void Main(string[] args)
{
var b = new B();
b.Method2();
Console.ReadLine();
}
}
class A
{
public virtual void Method1()
{
Console.WriteLine("Method1 in class A");
}
public void Method2()
{
Method1();
}
}
class B : A
{
public override void Method1()
{
Console.WriteLine("Method1 in class B");
}
}
The rule is "overriding member in the most derived class", which in this case would be "B".
B.Method1() is called due to the override.
B.Method1 is called because it is overridden in the class definition.
The question is a little ambigious...but...
obk.method2() is called. In turn, it calls obk.Method1, which, since it is an instance of B, has been overridden by B.Method1. So B.Method1 is what eventually gets called.
As everybody else has said, B.Method2 gets called. Here is a few other pieces of information so you understand what's going on:
((A)B).Method2();
B.Method2();
These will both call B.Method1() because it was properly overridden. In order to call A's Method1, there must be a base.Method1() call made from B (which is often but not always done in B.Method1's implementation).
If, however, B was defined in this way:
class B:A {
new public void Method1() { }
... then A's Method1() would be called because Method1 was not actually overridden, it was hidden and tucked away outside the rules of polymorphism. In general, this is typically a bad thing to do. Not always, but make sure you know very well what you're doing and why you're doing it if you ever do something like this.
On the flip side, using new in this way makes for some interesting interview questions as well.

Categories

Resources