Expand Generic Constraints for constructors
Currently when declaring a generic constraint on a Type parameter
ie.
public void DoSomething<T>() where T : new() { /* do something */ }
You can't specify that T has a constructor with specific parameters:
ie.
public void DoSomething<T>() where T : new(string, int) { /* do something */ }
11 comments
-
Giuseppe Lippolis
commented
another constraint interested to implement, it is a constraint that verifies if the generic type defined implements a specific generic Interface.
example:public interface ISelectableItem <TValue>
{
bool IsSelected {get; sets;}
TValue Value {get; sets;}
}public class SelectableCollection <TItem>: ObeservableCollection <TItem>
where TItem: ISelectableItem <?>
{
public void SelectAll()
{
foreach item in this
item.IsSelected = true;
}
} -
Marius Goppelt
commented
... and please regard visibility. Currently, new constraint is always assumed as public. It suffices if the method which calls "Invoke" has sufficient access to the constructor. This is very useful for a factory pattern, where I don't want to expose the constructor.
And don't forget VB.NET while you are at it! ;-)
-
CSharpJohn
commented
@michael >> where T : int or long or float or double <<
The issue is the lack of good generic math, specifically the lack of parent types or interfaces for int, long, float... like INumber, IInteger, IFloat.
This said, I agree re; generic constraints
ValueType does not cut it. -
Rich Brightons
commented
Yes Definitely, although you can do it via a static method.
-
Remigiusz Samosiuk
commented
Seems that I'm asking for the same
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2268973-virtual-static-method-in-interfaces-generics -
Mike Bursill
commented
Absolutely!
-
David
commented
I like this. Here is yet another suggestion on the same line...
as far as I'm aware, you can't do the following:public void DoSomething<T>() where T : Nullable
OR
public void DoSomething<T>() where T : NOT(Nullable)or somehow specify that T can (or cannot) be null. Recently I wanted to allow an "int?", or "long?" or "double?" (etc.) but not an "int", "long", or "double" but couldn't figure out how to do this. You CAN do this:
public void DoSomething<T>() where T : class
but that's not quite the same thing.
-
chha
commented
Yes, that's something I would also look forward to.
Language: VB.NET
-
Kent Boogaart
commented
-
Michael Paterson commented
@Ulrich,
I could get behind that one too.
-
Ulrich Bu
commented
Yes. Another suggestion:
public T Add(T a, T b) where T : int or long or float or double
{
return a + b;
}