Reputation: 13406
I have an issue which I can't seem to solve.
Suppose I have classes set up like this:
public abstract class GenericCustomerInformation
{
//abstract methods declared here
}
public class Emails : GenericCustomerInformation
{
//some new stuff, and also overriding methods from GenericCustomerInformation
}
public class PhoneNumber : GenericCustomerInformation
{
//some new stuff, and also overriding methods from GenericCustomerInformation
}
Now suppose I have a function setup like this:
private void CallCustomerSubInformationDialog<T>(int iMode, T iCustomerInformationObject)
{
//where T is either Emails or PhoneNumber
GenericCustomerInformation genericInfoItem;
//This is what I want to do:
genericInfoItem = new Type(T);
//Or, another way to look at it:
genericInfoItem = Activator.CreateInstance<T>(); //Again, does not compile
}
In the CallCustomerSubInformationDialog<T>
function, I have a variable of the base type GenericCustomerInformation
, which I want to instantiate with whatever is coming in T
( one of the derived types: either Emails
or PhoneNumber
)
An easy thing would be to use a bunch of if
conditions, but I don't want to do anything conditional, as that will make my code much bigger than it needs to be ..
Upvotes: 1
Views: 264
Reputation: 720
something like this maybe? (or have I misunderstood?)
private void CallCustomerSubInformationDialog<T>(int iMode, T iCustomerInformationObject) where T: GenericCustomerInformation, new()
{
//where T is either Emails or PhoneNumber
GenericCustomerInformation genericInfoItem;
//This is what you could try to do:
genericInfoItem = new T();
}
NB: Note the constraints on T...
Upvotes: 1