Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How specialize member type for a derived class in C#?

Tags:

c#

I would like to do something like this:

enter image description here

Where Plan has a Contact Property and there is a specialization of Plan and Contact.

I tried

abstract class Contact { }

class SpecialContact : Contact { }

abstract class Plan {
   public virtual Contact contact;
}

class SpecialPlan : Plan {
   public override SpecialContact contact;
}

But the type override are forbidden in C#.

How can I model this and specialize the sub property of a sub class?

I Just need to enforce that the SpecialPlan will only have SpecialContact.. not any other Contact

like image 659
Daniel Santos Avatar asked Feb 04 '26 17:02

Daniel Santos


1 Answers

void Main()
{
    var sp = new SpecialPlan();
    sp.Contact = new SpecialContact(); // new Contact(); won't compile
}

abstract class Contact
{
}

class SpecialContact : Contact
{
}

abstract class Plan<T> where T: Contact
{
    public T Contact { get; set; }
}

class SpecialPlan : Plan<SpecialContact>
{
}

If you want to override the get/set property.

void Main()
{
    var sp = new SpecialPlan();
    sp.Contact = new SpecialContact(); // new Contact(); won't compile
}

abstract class Contact
{
}

class SpecialContact : Contact
{
}

abstract class Plan<T> where T: Contact
{
    protected T contact;
    public virtual T Contact { get { return contact; } set { contact = value; } }
}

class SpecialPlan : Plan<SpecialContact>
{
    public override SpecialContact Contact { get { return contact; } set { contact = value; } }
}
like image 97
Han Avatar answered Feb 06 '26 07:02

Han



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!