Override a property in a subclass from the Baseclass interface

I am having a problem rewriting a property that comes from an interface. I got one base class that implements the interface. This class has 10 subclasses. In some cases, subclasses need to rewrite a property that comes from the interface.

My problem is that I am accessing a property without knowing what type of class the object has, and the object always returns the property value of the base class instead of the property value of the overridden subclass.

Sample code simplified:

public interface Inf { string Info { get; } } public class BaseClass : Inf { public string Info { get { return "Something"; } } } public class SubClass : BaseClass { new public string Info { get { return "Something else"; } } } 

in another class, I have to access the property, I do not know if the object is a type of base or subclass at the moment

 List<BaseClass> listBase = new List<BaseClass>(); listBase.Add(new BaseClass()); listBase.Add(new SubClass()); foreach (BaseClass obj in listBase) { Console.WriteLine(obj.Info); } 

Output:

 Something Something 

desired conclusion:

 Something Something else 

((SubClass) obj) .Info displays "Something Else", but at this specific moment I don't know which class is the object. (I have arround 10 different subclasses).

Do I need to throw all objects at him? I got 100-200 objects and 10 different classes in this list. Or is there any other way to do this?

any help appreciated :)

+6
source share
3 answers

You must make an implementation of the virtual property in the base class and put an override instead of new in the implementation in the derived classes. This should fix the problem.

Currently, the only class that provides the implementation of the Info property from the Inf interface is your BaseClass . According to your code, the compiler believes that the SubClass derived class introduces a new property with the same name, which is legal. Such a property will be available only when using the class directly, and not through the interface.

+8
source

You are doing it wrong. Do the following:

  • declare a base class property using the virtual
  • add override keyword next to subclass property declaration
 public class BaseClass : Inf { public virtual string Info { get { return "Something"; } } } public class SubClass : BaseClass { public override string Info { get { return "Something else"; } } } 

In this case, the result will be what you expect.

Read more about redefinition and polymorphism here: Polymorphism (C # Programming Guide)

+3
source

You broke the chain by a "new" property. You need to override it:

 public interface Inf { string Info { get; } } public class BaseClass : Inf { public virtual string Info { get { return "Something"; } } } public class SubClass : BaseClass { public override string Info { get { return "Something else"; } } } 
+2
source

Source: https://habr.com/ru/post/949307/


All Articles