C# Inherited member variables behaving undexpectedly

Posted by Nilbert on Stack Overflow See other posts from Stack Overflow or by Nilbert
Published on 2010-05-19T16:35:03Z Indexed on 2010/05/19 16:40 UTC
Read the original article Hit count: 229

Filed under:
|
|
|
|

If I have a class like this:

class A {
    public string fe = "A";
}

And a class that inherits from it like so:

class B : A {
    public string fe = "B";
}

Visual C++ will tell me that B.fe hides A.fe so I should use the new keyword. So I change class B to look like:

class B : A {
    public new string fe = "B";
}

And then I have a function that takes an A (but, by virtue of inheritance, will also take a B) like this:

class D {
    public static void blah(A anAObject) {
        Console.Writeline(A.fe);
    }
}

Even when I pass it an instance of a B object, which it will take without question, it will print "A"! Why is this, and how can I make it work how I want without setting the variable in the constructor?

© Stack Overflow or respective owner

Related posts about c#

Related posts about class