Is there an equivalent of MyClass?

Is there an equivalent of MyClass?

  • Comments 8

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.

[Author: Jon Skeet]

Leave a Comment
  • Please add 3 and 1 and type the answer here:
  • Post
  • Isn't MyClass just something like

    public class MyObject {
    public virtual void DoSomething() {
    Console.WriteLine("I did something!");
    }

    public void Process() {
    ((MyObject)this).DoSomething(); // MyClass.DoSomething()
    }
    }

    ?
  • No - just casting doesn't remove the fact that the call is made polymorphically. (i.e. if a subclass overrides DoSomething, then calls Process, it's the subclass's version of DoSomething which will be called.)
  • Wow, I did not realize that... Is there any way to actually call this classes method instead of the overriden one?
  • Only by making it non-virtual.
  • Is there a reason this was added to VB.NET and not C#? I looked at the difference between the code, the VB.NET IL does a call MyObject.Process while the C# IL does a callvirt MyObject.Process

    Obvious why this happens, but what about adding it to C#, or is a bad feature to have? I have never used it, just wondering why ...
  • Do you know if MyClass is something that the VB team went out of their way to provide by doing lots of work or is this natively supported in CIL?
  • Adam :
    You can use "base" but you need a new class :)

    public class YourObject : MyObject {
    public void Process() {
    base.DoSomething(); // base and this make a lot of difference here
    }
    }

    public class HisObject : YourObject {
    public override void DoSomething() {
    Console.WriteLine("Process never calls it!");
    }

  • it's the subclass's version of DoSomething which will be called
Page 1 of 1 (8 items)