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...)
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.0none of these have static type-checking etc, though.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With