How to pass a generic parameter type to a method called from a constructor?

Here is the constructor:

public PartyRoleRelationship(PartyRole firstRole, PartyRole secondRole) { if (firstRole == secondRole) throw new Exception("PartyRoleRelationship cannot relate a single role to itself."); if (firstRole.OccupiedBy == null || secondRole.OccupiedBy == null) throw new Exception("One or both of the PartyRole parameters is not occupied by a party."); // Connect this relationship with the two roles. _FirstRole = firstRole; _SecondRole = secondRole; T = _FirstRole.GetType().MakeGenericType(); _SecondRole.ProvisionRelationship<T>(_FirstRole); // Connect second role to this relationship. } 

On the last line, where it calls the ProvisionRelationship on _SecondRole, it gives me a runtime error: Type or namespace T cannot be found ...

How can I (a) correctly assign T, or (b) pass a generic type using the constructor? I looked through quite a few posts, but may have missed something due to a lack of understanding. Any help on this would be greatly appreciated.

+7
source share
3 answers

Your class must be shared. Therefore, the PartyRoleRelationship should look like this:

 public class PartyRoleRelationship<T> { public PartyRoleRelationship(T arg, ...) { } } 

Read more about common classes here:

http://msdn.microsoft.com/en-us/library/sz6zd40f(v=vs.80).aspx

http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx

Edit:

Perhaps you simplify the code a bit and do it like this:

 public class RoleRelationship<T> { public RoleRelationship(T firstRole, T secondRole) { if (firstRole.OccupiedBy == null || secondRole.OccupiedBy == null) throw new Exception("One or both of the Role parameters is not occupied by a party."); // Connect this relationship with the two roles. _FirstRole = firstRole; _SecondRole = secondRole; _SecondRole.ProvisionRelationship<T>(_FirstRole); } } 
+12
source

Create a generic class, where generic type T is the base class type of PartyRole:

 public class PartyRoleRelationship<T> where T : PartyRole { T _FirstRole; T _SecondRole; public PartyRoleRelationship(T role1, T role2) { _FirstRole = role1; _SecondRole = role2; role1.ProvisionRelationship(role2) } public ProvisionRelationship(T otherRole) { // Do whatever you want here } } 
+4
source

If you know the _FirstRole type statically (is it PartyRole?), You can simply use this:

 _SecondRole.ProvisionRelationship<PartyRole>(_FirstRole); 
0
source

All Articles