I’m trying to override a property in my program.
Here is basically what I’m trying to do :
class A { public int test = 7; }
class B : A { public int test = 8; }
class Program
{
static void Main(string[] args)
{
A test1 = new A();
A test2 = new B();
Console.WriteLine(test1.test);
Console.WriteLine(test2.test);
}
}
This displays 7 in both case when I’d like it to display 8 in the 2nd case….
I’ve tried virtual and override as well as new (public new int test = 8;)
But it doesn’t seem to work
And yes I know I should use private and getters. I just want to know if it’s possible ?
Edit : I’m not a native C# programmer so forgive me if i mix the terms (such as field and propertys)!
The problem is that
int testis not a property, it is a public field. Fields cannot be overriden.Here is an example of overriding a property:
Here is a demo of this code on ideone.