VSO
VSO

Reputation: 12646

Generic Method Taking A Type and Returning Instance of that Type?

I have a bunch of models which have the same properties - greenPeople, bluePeople, etc. For each of these, I have a controller, and in the post, I push their picture to some server and make a SQL entry describing the entry. Actually, my models are GreenPeoplePicture, BluePeoplePicture, etc.

So I have something like:

GreenPeoplePicture greenPeoplePicture = new GreenPeoplePicture(); 
greenPeoplePicture.Name = "blah"
greenPeoplePIcture.Date = DateTime.UtcNow;

etc. Once it's filled out I stream to the remote server and then save "greenPeoplePicture" to the GreenPeoplePictures table. I want to write a generic method for this. I can't wrap my head around how to pass the type itself without passing any variable, since I want to do:

GreenPeoplePicture greenPeoplePicture = new GreenPeoplePicture(); 

in the method, and also have the return type be GreenPeoplePicture. I am sure this post is tantamount to "I can't code and don't understand generics," but I tried - at least tell me whether or not it's possible. MSDN and tutorialspoint aren't much help.

Upvotes: 1

Views: 106

Answers (2)

mrjoltcola
mrjoltcola

Reputation: 20852

For generics, you can use default(T) to initialize a variable to the default value, or you can use new T() to create an instance. In order to use new(), you should narrow the specificity of the type by adding a type constraint of new()

public T Factory<T>() where T : new() {
    return new T();
}

or

    return default(T);

If you want to handle the different properties of each type, then generics won't completely solve that, you'll have to supplement it with reflection to lookup properties dynamically.

Upvotes: 1

Rob
Rob

Reputation: 27367

Something like this?

public T MakeColourPerson<T>() where T : new() {
    return new T();
}

var myPerson = MakeColourPerson<GreenPeoplePicture>();

Also, if GreenPeoplePicture and BluePeoplePicture have anything in common (for example, if they inherit from ColourPeoplePicture, you can change the where to be this:

where T : ColourPeoplePicture, new() to be more precise

This will allow you to do more useful things inside MakeColourPerson

public T MakeColourPerson<T>() 
    where T : ColourPeoplePicture, new() 
{
    var colourPerson = new T();
    colourPerson.Name = "blah";
    colourPerson.Date = DateTime.UtcNow;
    return colourPerson;
}

Assuming ColourPeoplePicture exposes the properties Name and Date

Upvotes: 2

Related Questions