Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Property in Subclass from Baseclass Interface

Tags:

c#

.net

interface

i got a problem with overwriting a property which comes from an Interface. I got one Base Class which implements an Interface. This class has arround 10 Subclasses. The subclasses should overwrite the property which comes from the Interface in some cases.

My problem is, that i access the property while not knowing what type of class the object has and the object allways returns the base class property value instead of the overwritten subclass property value.

Example 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 dont know if the object is type of base or subclass at this 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

wanted output:

Something
Something else

((SubClass)obj).Info would output "Something else" but at this certain moment i dont know what kind of class the object is. (i have arround 10 different subclasses).

Do i have to cast all objects to it's real class? i got like 100-200 objects in this list and arround 10 different classes. Or is there any other way to do this?

any help appreciated :)

like image 692
Koryu Avatar asked Jul 12 '13 10:07

Koryu


1 Answers

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

Currently, the only class that provides the implementation for the property Info from the interface Inf is your BaseClass. According to your code, compiler thinks that the derived class SubClass introduces a new property with the same name, which is legal. Such property would be accessible only when you use the class directly, not through an interface.

like image 57
Sergey Kalinichenko Avatar answered Sep 30 '22 13:09

Sergey Kalinichenko