Reputation: 622
Is it possible in C# to have a method of a generic driven class require new, but not require new on the whole class?
public class Response<T> //not where T:new()
{
public void AddTotal<T>() where T : new()
{
var totaledObject = new T();
// do all the useful stuff I need with the new generic
}
}
I use this response for many different scenarios, the T does not always have a new(), and for those scenarios I will not use the AddTotal function, but for a few I would like to have it. Is this possible?
Note: I know I can do a different generic variable name and just pass that to the function, but this breaks the indication that it has to be of the same type as T.
Upvotes: 1
Views: 329
Reputation: 415840
You can get around this by pushing the problem out to the calling code. Add an argument to either have the calling code provide the object instance you need or have the calling code provide the method you need to create the object:
public void AddTotal<T>(T totaledObject)
{
// do all the useful stuff I need with totaledObject
}
//call it: AddTotal(new Object())
or
public void AddTotal<T>(Func<T> createObject)
{
var totaledObject = createObject();
// do all the useful stuff I need with the new generic
}
The trick with this option is that you can't just pass a constructor to that object. You have to wrap calls in another delegate, which can be done with a quick lambda expression:
AddTotal(() => new Object());
Upvotes: 2
Reputation: 5109
You don't have to constrain T to new (). Just allow it. Use 'where T : class, new()' as your class constraint. You don't need anything on the method as new T() can now be used.
Upvotes: 0
Reputation: 149538
Is it possible in C# to have a method of a generic driven class require new, but not require new on the whole class?
Only if you specify different type parameter, which you don't want to do. A generic type parameter constraint exists for any generic type argument you specify. As you want T
for the class and method declaration to be the same T
, the constraint will exist for both.
If you want to specify another generic type parameter, you could do something hacky like this:
public class X<T>
{
public void Y<OtherT>() where OtherT : T, new()
{
}
}
Thus constraining OtherT
to be of type T
declared in the class or a derivative. There's no guarantee there will be an exact match on the type.
Upvotes: 0