Reputation: 2866
I am using ASP.Net Web API 2 and want to create some complex input parameter classes.
I have classes in my library as
public class GrandParent
{
public int Id {get;set;}
public string GrandParentName {get;set;}
}
public class Parent : GrandParent
{
public string ParentName {get;set;}
}
Now I only need Parent class properties in my child class and I am doing so
public class Child : Parent
{
public string ChildName {get;set;}
}
When I create object of Child class, I want only two properties, which are
Child objChild = new Child();
objChild.ParentName;
objChild.ChildName;
I don't want GrandParentName property with objChild. Is there any way to skip grand parent classes in inheritance structure as I want to pass this class as API action parameter.
I am feeling lack of multiple inheritance in C# here.
Upvotes: 2
Views: 1280
Reputation: 2357
I may be misunderstanding something but I think you are going too far with inheritance. You might look to the composite pattern.
I think you are confused between the role of each object compared to each others and inheritance. I am not sure you need all these classes. Here is what I would do :
interface IPerson
{
public int Id { get; set; }
public string Name { get; set; }
public string ParentName { get; }
}
class Person : IPerson
{
public int Id { get; set; }
public string Name { get; set; }
protected IPerson Parent { get; set; }
public string ParentName { get { return this.Parent != null ? this.Parent.Name : String.empty; } }
public Person(IPerson parent = null)
{
this.Parent = parent;
}
}
And once you have this, you can achieved what you want :
var grandParent = new Person();
var parent = new Person(grandParent);
var child = new Person(parent);
I hope I didn't miss any crucial point :D.
Upvotes: 2
Reputation: 87
As it seems, you may need to change your GrandParent from class to interface, then that might work, if you need those properties just make extra class that implements interface. Remember that you can implement as many interfaces as you need on a single class. And still they have common name for use in Lists and stuff.
fharreau gave example.
If you want better example you should make some data diagram concerning data in question.
Upvotes: 0