Reputation: 11687
I came across a question recently and I have not worked much on that in my past. I have a class named ObjectCreator
with a method Create
.
public static class ObjectCreator
{
// Create method
}
I should be able to call the Create
method in the following ways.
var obj1 = ObjectCreator.Create<Employee>();
var obj2 = ObjectCreator.Create<Client>();
var obj3 = ObjectCreator.Create<Company>();
and so on for any other type. Now how to implement the Create
method here? Remember Create method does not accept any parameters here. Can anyone help me to get a work around?
Upvotes: 1
Views: 101
Reputation: 68660
public static class ObjectCreator
{
public static T Create<T>() where T : new()
{
return new T();
}
}
I added the T: new()
constraint (which forces the type T
to have the default constructor) and the return statement just to illustrate one possible use case.
Upvotes: 4
Reputation: 11549
We already have Activator.CreateInstance Method which requires (not forces) a parameterless public constructor. If no suitable constructor found it throws an exception at runtime. Since dcastor's answer forces a compile time error it seems better.
var obj1 = Activator.CreateInstance<Employee>();
var obj2 = Activator.CreateInstance<Client>();
var obj3 = Activator.CreateInstance<Company>();
Upvotes: 2