Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic constraint: Enforce type to have static function and constructor with parameters

I know you can write:

class GenericClass<T> where T : new()
{ 

}

to enforce that T has an empty constructor.

My Qs are :

  1. can you enforce that T has a constructor with a specific type of parameter? Like:

    class SingletonFactoryWithEmptyConstructor<T> where T : new(int)
    
  2. can you enforce that T has a static function (let's say, void F()) so that you can use this function inside the generic class? Like :

    class GenericClass<T> where T : void F()
    { 
       void G ()
       {
           T.F();
       }
    }
    

    I know you can specify that T implements an interface but I don't want that. I want to specify that T has a static function.

like image 209
geth Avatar asked May 07 '11 07:05

geth


People also ask

Which of the following generic constraints restricts the generic type parameter to an Object of the class?

Value type constraint If we declare the generic class using the following code then we will get a compile-time error if we try to substitute a reference type for the type parameter.

What does the generic constraint of type interface do?

Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.

What are generic type constraints?

C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.


1 Answers

No, there's nothing like this in C#.

I've previously suggested that "static interfaces" could express this reasonably neatly. They'd only be useful for generic type constraints (I suspect, anyway) but then you could express:

  • Constructors with arbitrary parameters
  • Static methods and properties
  • Operators

The last of these points is particularly interesting in my view, allowing things like a generic "Average" method over numeric types with suitable addition and division operators.

I believe some folks at MS have thought about something similar, but I haven't heard anything to suggest they're actively working on it.

like image 197
Jon Skeet Avatar answered Sep 21 '22 19:09

Jon Skeet