Josh
Josh

Reputation: 8477

Set Generic to a new instance in C#

I have a method that takes a Generic parameter. I've restricted the type to one of two. Within the method I want to set call one of the two constructors.

Code:

internal static void CreateAddress<T>(out T address, bool isSave, int? cID) where T: Address_Accessor, Address
 {
   DateTime dt= DateTime.Now;
   int? eID = 1;
   int? sID = 50;

   if (typeof(T) == typeof(Address_Accessor))
     address = new Address_Accessor(dt, eID , sID);
   else
     address = new Address(dt, eID, sID);
}

The compile failure says:

Cannot implicitly convert type 'Address_Accessor' to 'T'. An explicit conversion exists (are you missing a cast?)

Upvotes: 0

Views: 135

Answers (2)

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

I don't understand why you need that code but you can convert result objects to T until return it:

object result = typeof(T) == typeof(Address_Accessor)
  ? (object) new Address_Accessor(dt, eID , sID)
  : (object) new Address(dt, eID, sID);

address = (T)result;

Upvotes: 1

sll
sll

Reputation: 62544

As a straightforward solution (not having any details regardign method usage cases) if Address and Address_Accessor both represents some common entity - just introduce a common interface and restrict T to implement this interface, then you would be able insatntiating any of class which implements IAddress and setting to the IAddress reference (behind T).

interface IAddress
{
}

class Address_Accessor : IAddress
class Address : IAddress

internal static void CreateAddress<T>(out T address, bool isSave, int? cID) 
where T: IAddress  
{ 
}

I feel there some design issues around, could you please post a code which calling CreateAddress() method for both Address and Address_accessor cases? Perhaps you are looking for a some kind of abstract factory?

Upvotes: 1

Related Questions