Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MyClass equivalent in C#

Tags:

c#

vb.net

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.

like image 928
Damien_The_Unbeliever Avatar asked Jul 26 '11 14:07

Damien_The_Unbeliever


3 Answers

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().

like image 74
Heinzi Avatar answered Nov 14 '22 20:11

Heinzi


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.

like image 41
Numenor Avatar answered Nov 14 '22 19:11

Numenor


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");
    }
}
like image 1
George Duckett Avatar answered Nov 14 '22 18:11

George Duckett