bluray
bluray

Reputation: 1953

C# cast child to parent

Hello I have this class:

class A{
 public string P1{get; set;}
 public string P2{get; set;}
 ...
 public string PX{get; set;}
}

This class is in DLL and i don't need to change it. But I would like to add some property, so I created class B:

class B : A{
  public bool IsSelected{get;}
}

It's ok, but now I would like to convert class B to A (without IsSelected property):

B b = new B();
A a = (A)b;

Variable a has IsSelected. Is is way how to do it? Or how to design this model better?

Upvotes: 1

Views: 1352

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273169

One possible solution is to decide that not B is-an A but B has-an A :

class B 
{
  public A A { get;  }
  public bool IsSelected{get;}
}

Upvotes: 1

Kevin Gosse
Kevin Gosse

Reputation: 39007

Object A is being send using WCF and when contains IsSelected property, it can not be sent. In application I need A + IsSelected but when I need send it, A must be without IsSelected

You can tell the WCF serializer to ignore the field by applying the IgnoreDataMember attribute:

class B : A{
  [IgnoreDataMember]
  public bool IsSelected{get;}
}

Upvotes: 1

Related Questions