Constraints in C# vNext + 1

I was reading a post on Troy Magennis’ blog today about his set of LINQ extension methods that he is creating and something struck me about the notation he was using to describe some of his methods.

Example: public static [numeric type] Min(this IEnumerable<[numeric type]> source, int defaultValue)

The interesting bit is “[numeric type]”. It got me thinking about some of the things that we loose without having a full power constraint system in C# 2.0 around what types you accept and reject. I’d actually like the ability to constrain which types are accepted based on what methods they implement.

I wonder what the syntax would need to look like to be that expressive – and how tricky would it be to do at compile time and at runtime? It would probably also require a level of duck-typing support in C#, which is something that VB vNext will have (hopefully it hasn’t been cut).


3 thoughts on “Constraints in C# vNext + 1

  1. Andrew Matthews


    What C# vNext requires is either the option to define operations in interfaces, or (much more preferable) to perform method-based static type checking a la C++. Method based constraint checking would determine whether the type argument supports required methods without having to define generic argument constraints.

    The ‘new()’ constraint is a method-level constraint referring to method types that can’t appear in interfaces, so it’s not as if the idea is alien to the C# generics system. I don’t know why it was removed in favour of the interface level constraint checking.

    To define a constraint on a numeric type you would have to invent a common base class for all numeric classes (as in Java). That would probably be out of the question at this stage (despite the existence of a Numeric class in the framework), so reflection is the only alternative I guess.

    I touched on that issue here:

    cheers, Andrew

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s