Omer Eliyahu
Omer Eliyahu

Reputation: 19

C# OOP specific params while extending class

I have a class ClassA that has a protected property of type class AttA, a class ClassB that extends from ClassA and a class AttB that extends from AttA.

In class ClassA I want to use the property AttA but in class ClassB I want to use the more specific property AttB.

Is there a way to do so?

class ClassA
{
    protected AttA att;

    public void MyMethod()
    {
        // using att as AttA
    }
}
class ClassB : ClassA
{
    public override void MyMethod()
    {
         // Want to use att as AttB (if possible without downcasting)
    }
}

Thanks.

Upvotes: 0

Views: 59

Answers (1)

user12031933
user12031933

Reputation:

A simple way is to use the new keyword:

class ClassA
{
  protected AttA att;
  public virtual void MyMethod()
  {
  }
}

class ClassB : ClassA
{
  new protected AttB att;
  public override void MyMethod()
  {
  }
}

class AttA
{
}

class AttB : AttA
{
}

But this may causes problems on using polymorphism because writing:

var b = new ClassB();

//b.att is type of AttB here

var a = (ClassA)b;

//a.att is type of AttA here and it is not the same variable

In fact, there is two fields att depending of the type you manipulate, so be carefull in the classes implementations especially when calling base members from child class.

Since the field is protected this problem is limited.

On the contrary this may be exactly what is needed.

https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/new-modifier


I tried to find a generic solution, but since C# does not support true generic polymorphism, and we can't constraint a generic type parameter on one type for one class type, this is impossible, as I know - or it requires writing some code using reflection which can be overengineered here unless it is necessary (thus it will be possible to have the same variable between classes hierarchy exposing the desired polymorphed type).

Upvotes: 1

Related Questions