Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritence in C# question - is overriding internal methods possible?

Tags:

c#

inheritance

Is it possible to override an internal method's behavior?

using System;

class TestClass
{
    public string Name { get { return this.ProtectedMethod(); } }

    protected string ProtectedMethod()
    {
        return InternalMethod();
    }

    string InternalMethod()
    {
        return "TestClass::InternalMethod()";
    }
}

class OverrideClassProgram : TestClass
{   // try to override the internal method ? (doesn't work)        
    string InternalMethod()
    {
        return "OverrideClassProgram::InternalMethod()";
    }

    static int Main(string[] args)
    {
        // TestClass::InternalMethod()
        Console.WriteLine(new TestClass().Name);
        // TestClass::InternalMethod() ?? are we just screwed?
        Console.WriteLine(new OverrideClassProgram().Name); 
        return (int)Console.ReadKey().Key;
    }
}
like image 728
Jeff Dahmer Avatar asked Nov 24 '25 12:11

Jeff Dahmer


1 Answers

I think you've got something confused here. There is an actual keyword "internal", is this what you want?

internal string InternalMethod()
{
    return "TestClass::InternalMethod()";
}

But I think what you're really looking for is the "virtual" keyword. This allows you to do an override: Parent Class

protected virtual string InternalMethod()
{
    return "TestClass::InternalMethod()";
}

Child Class

protected override string InternalMethod()
{
    return "TestProgram::InternalMethod()";
}

Using the "new" keyword is valid, but it completely reimplements the method. I.e. it breaks polymorphism.

Edit: Here's a link.

like image 94
xanadont Avatar answered Nov 26 '25 00:11

xanadont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!