Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does .Net support curried generics?

Suppose we have a nested generic class:

public class A<T> {
    public class B<U> { }
}

Here, typeof(A<int>.B<>) is in essence a generic class with two parameters where only the first is bound.

If I have a single class with two parameters

public class AB<T, U> { }

Is there a way to refer to "AB with T=int and U staying open"? If not, is this a C# limitation, or a CLR limitation?

like image 797
configurator Avatar asked Apr 08 '11 23:04

configurator


People also ask

What are .NET generics?

NET: A generic type definition is a class, structure, or interface declaration that functions as a template, with placeholders for the types that it can contain or use.

Why are generics used in C#?

Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes. The . NET class library contains several generic collection classes in the System.

What is Generics in C# Real Time example?

Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.

Do generics increase performance?

With using generics, your code will become reusable, type safe (and strongly-typed) and will have a better performance at run-time since, when used properly, there will be zero cost for type casting or boxing/unboxing which in result will not introduce type conversion errors at runtime.


2 Answers

Apparently it can't be done in C#, you have to specify either both type parameters, or none.

And it doesn't seem to be supported by the CLR either, A<int>.B<> and A<string>.B<> refer to the same type:

Type t1 = typeof(A<int>).GetNestedType("B`1");
Type t2 = typeof(A<string>).GetNestedType("B`1");
// t1.Equals(t2) is true

The enclosing type of both types is A<> (open generic type)

EDIT: further testing shows that typeof(A<int>.B<string>) is actually a generic type of arity 2, not a nested generic type of arity 1... typeof(A<int>.B<string>).GetGenericArguments() returns an array with typeof(int) and typeof(string). So typeof(A<int>.B<>) would actually be equivalent to (A.B)<int, >, which isn't supported (a generic type can't be partially closed)

like image 129
Thomas Levesque Avatar answered Oct 11 '22 18:10

Thomas Levesque


Is this what you have in mind?

   class AB<T, U>
   {
      protected T t;
      U u;
   }

   class C<U> : AB<int, U>
   {
      public void Foo()
      {
         t = 5;
      }
   }
like image 45
GregC Avatar answered Oct 11 '22 17:10

GregC