explain inheritance method override

Here are two classes :

public class ClassA
{
    public string result()
    {
        return "ClassA_Result";
    }
}

and

public class ClassB : ClassA
{
    public string result()
    {
        return "ClassB_Result";
    }
}

When I create an instance of ClassB the result I'm getting is ClassB_Result. I'm expecting the result to be ClassA_Result

 ClassB objB = new ClassB();

 string b = objB.result();    //result is `ClassB_Result`
Jon Skeet
people
quotationmark

Firstly, you're not overriding the result() method - and indeed you can't, because it's not virtual.

The compiler should be giving you a warning like this:

warning CS0108: 'ClassB.result()' hides inherited member 'ClassA.result()'. Use the new keyword if hiding was intended.

Always always read the compiler warnings. They're there to help you.

You should have a virtual modifier on the method in ClassA, and the override modifier on the method in ClassB. I'd also encourage you to follow .NET naming conventions - I know this was just a sample, but it's worth following conventions even in dummy code. (result should be Result.)

Now even when you've fixed the code like that, you'll still get ClassB_Result - because you're creating an instance of ClassB. The difference would come if you write:

ClassA objB = new ClassB();
string b = objB.result();

With that snippet, in your current code it will give a result of ClassA_Result because the method isn't being called virtually. With the fixed code, it would give a result of ClassB_Result because the override in ClassB would be called. Currently, your method in ClassA is entirely irrelevant, because the compile-time type of objB is ClassB.

people

See more on this question at Stackoverflow