Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# generics support type signature constraints?

Tags:

c#

.net

generics

One of the benefits with C++ templates is that you (implicitly) can require a certain type signature (e.g. type T needs to have a function x that takes no parameters and returns an int). Does C# generics support something similar?

I am aware of constraints based on base class or interface but this is not what I am looking for.

(As a C++ programmer learning C# I might be mistaken that this is a feature that you would want in C#. Any comments on this would be appriciated as well...)

like image 620
Tobias Furuholm Avatar asked Jul 01 '11 20:07

Tobias Furuholm


2 Answers

Nothing except for the constraints you have already seen (which do, to be fair, cover a lot of common scenarios). There are some common workarounds:

  • dynamic, in 4.0
  • manual duck-typing using either reflection or IL generation etc

none of these have static type-checking etc, though.

like image 182
Marc Gravell Avatar answered Sep 23 '22 04:09

Marc Gravell


Yes, through an interface. You can define a generic object that has a type that must have a specific interface implemented. Within that interface, you would essentially be forcing any object added to that generic, list for instance, to have a specific signature.

Whether or not that's what you're not looking for, that's how you accomplish it. :)

like image 33
George Johnston Avatar answered Sep 22 '22 04:09

George Johnston