Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a generic type parameter 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 ProvisionRelationship on _SecondRole, it's giving me the run-time error: Type or namespace 'T' could not be found...

How do I either (a) properly assign T, or (b) pass a generic type with the constructor? I've been looking through quite a few posts, but may have missed something due to a lack of understanding. Anyone's help on this would be greatly appreciated.

like image 415
Phil Avatar asked Mar 03 '13 22:03

Phil


2 Answers

Your class needs to be generic. So PartyRoleRelationship needs to look like this:

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

Read more about generic 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:

You could probably simplify you 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);
    }
}
like image 178
Cheesebaron Avatar answered Oct 07 '22 19:10

Cheesebaron


Make a generic class where the generic type T is a type of the base class 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
     }

}
like image 43
Moop Avatar answered Oct 07 '22 20:10

Moop