Well, you have a few compiler errors, but here is a corrected version based on your example.
class Base {
public int abc = 3;
}
class Derived : Base {
public int abc = 2;
}
static void Main(string[] args)
{
Derived foo = new Derived();
Console.WriteLine(foo.abc);
Base bar = new Derived();
Console.WriteLine(bar.abc);
}
The first line will output a 2
. The second line will output a 3
. The reason why is because, unless you explicitly override a member of a base class, it will only apply to instances of the concrete class.
In your derived class, you're essentially using the new
modifier keyword without explicitly using it. The new
keyword hides a base member, however if the concrete class is cast as its base type, the new property doesn't get used and can't be accessed until it is "cast-down" to the concrete class again.
In the second example, the Derived
class is cast as a Base
, so it will use the Base
abc
property. If you were to use the override
keyword, then the second line would also output a 2
.
Edit: Keep in mind that in order to be allowed to use override
on the Derived
class, you need to mark Base.abc
with the virtual
keyword. Also, you can't make fields virtual
. You need to use Properties to use the virtual
keyword. You shouldn't be exposing fields to begin with though, so this is generally never a problem.