user2887486
user2887486

Reputation: 89

Generic <T> and 2 base class inheritance

I have a question and am getting a little stumped on this one. It's probably easy but I'm just missing it.

If I have a class what contains necessary structures and the structures can inherit. I need a generic method what that an be passed to and then used. For example, let's say I have a structure Test, Test-A which inherits from Test. Then I have a MyTest and MyTest-B both which inherit from Test-A.

How can I create a method using T so that I can supply both MyTest and MyTest-B and I can use either of them in the method?

So:

public class Test
{
    public int Hello {get; set; }
}

pubilc class Test-A : Test
{  
   public string Name { get; set; }
}

public class MyTest : Test-A
{
   public string Last { get; set; } 
}

public class MYTest-B : Test-A
{
   public int Age {get; set; }
}

I need a method like:

private void MyList<T>(List<T> TestList) where T : **{not sure what this would be}**
{
    TestList.Age = 10;

    **OR** 

    TestList.Name = "Jane";
}

How or what am I missing (or not understanding) to be able to do that?

Any assistance would be greatly appreciated.

Upvotes: 1

Views: 105

Answers (2)

Mark Sowul
Mark Sowul

Reputation: 10600

How can I create a method using T so that I can supply both MyTest and MyTest-B and I can use either of them in the method?

     **TestList.Age = 10;**

     ...

How would this work if you passed in an object of type MyTest, given that MyTest doesn't have an Age property?

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564433

There is no constraint you could use which would match both of those conditions. The only way to handle this would be to use two, overloaded methods, as there is no shared contract.

Generic constraints only work if there is a base class or interface shared which all types implement, and use the same contract (ie: both have Name and Age properties).

Upvotes: 4

Related Questions