Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use <> (or <,>)?

Tags:

c#

At the moment I am struggling a bit with generic typeing.

While reading about it I sometimes encounter ISomeType<>.

E.g.:

Type generic = typeof(Dictionary<,>);

https://msdn.microsoft.com/en-us/library/system.type.makegenerictype%28v=vs.110%29.aspx

I can't really find any documentation on wat the empty <> means.

So: When should I use <> or <,>?

update:

As @dcastro stated, it is called open generics and more info can be found here: Generics -Open and closed constructed Types

update 2

As for the closure argument, this question is about the meaning of the syntax.

like image 377
Stefan Avatar asked Oct 12 '25 08:10

Stefan


1 Answers

An assembly can define, within the same namespace, multiple types with the same name, as long as the number of type arguments (generic parameters) differs for each type. Try for example:

var strA = typeof(Action).ToString();     // "System.Action"
var strB = typeof(Action<>).ToString();   // "System.Action`1[T]"
var strC = typeof(Action<,>).ToString();  // "System.Action`2[T1,T2]"
var strD = typeof(Action<,,>).ToString(); // "System.Action`3[T1,T2,T3]"

In C#, one can only use empty <...>, i.e. avoid specifying what the type parameters are, within the typeof(...) keyword.

Another example: typeof(Dictionary<,>).ToString() gives "System.Collections.Generic.Dictionary`2[TKey,TValue]". As you can see, in .NET (the CLI) the number of generic parameters is given by appending a backtick followed by digit(s).


Examples of use:

static bool IsDictionary(object obj)
{
  if (obj == null)
    return false;

  var t = obj.GetType();
  return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>);
}

static object GetDictionary(object a, object b)
{
  var t = typeof(Dictionary<,>).MakeGenericType(a.GetType(), b.GetType());
  return Activator.CreateInstance(t);
}

But if possible, avoid reflection and use compile-time types, for example (not quite equivalent to the above):

static Dictionary<TA, TB> GetDictionary<TA, TB>(TA a, TB b)
{
  return new Dictionary<TA, TB>();
}
like image 183
Jeppe Stig Nielsen Avatar answered Oct 15 '25 00:10

Jeppe Stig Nielsen