new constraint with type parameters #4532
-
I wanted to start a discussion around adding generic Right now, you can do the following (example from the docs): class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
} There are times where it would be beneficial to do something like this, but where the constructor has parameters. The proposal is to support that for generics, as follows: class ItemFactory<T> where T : new(int, string)
{
public T GetNewItem(int a, string b)
{
return new T(a, b);
}
} I don't know the complexities that could come with implementing such a feature in the language, so I won't speculate on that. The only downside I see with the feature from a usability perspective is that the constructors may not mean the same thing conceptually, even if they have the same parameters. It may be coincidental that they take the same parameters. In practice though, I think the class ItemFactory<T> where T : IMyInterface, new(int, string)
{
public T GetNewItem(int a, string b)
{
return new T(a, b);
}
} The current alternative is to use the class ItemFactory<T> where T : ISomeInterfaceWithSetters, new()
{
public T GetNewItem(int a, string b)
{
return new T
{
Val1 = a,
Val2 = b
};
}
} In some cases this works just as well as the proposed design, but that's not always the case. In some situations, you may need to do other work or validation in your constructor, so setting data via the initializer is inconvenient. Additionally, it would require exposing private fields via properties, which isn't ideal, even if those properties could be made |
Beta Was this translation helpful? Give feedback.
#769, #1330, #1574, #1626, #1633