2

Say I have something like

var T = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");

which is a nullable datetime.

T.FullName gives me:

"System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"

How can I extract DateTime? or Nullable<DateTime> as a string representation from the Type?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
David
  • 15,652
  • 26
  • 115
  • 156
  • 1
    see question: http://stackoverflow.com/questions/401681/how-can-i-get-the-correct-text-definition-of-a-generic-type-using-reflection; (this answer http://stackoverflow.com/a/6592598/1506454) – ASh Sep 10 '15 at 10:23
  • I missed it, should I delete the question? – David Sep 10 '15 at 10:24
  • I wrote a method for exactly this purpose 2 years ago (http://www.codeproject.com/Tips/621812/User-friendly-names-for-Types) but I really like the solution in the answer ASh pointed out! (http://stackoverflow.com/a/6592598/1506454) – Dennis_E Sep 10 '15 at 10:45

2 Answers2

0

Maybe in this way:

var T = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
Type nullableType = Nullable.GetUnderlyingType(T);
string typeName = nullableType != null ? nullableType.Name + "?" : T.Name;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Type.FullName returns the full assembly qualified name for the generic arguments. But the ToString() method will print a much more friendly name, maybe this is what you want:

System.Nullable`1[System.DateTime]

Please note that if the generic arguments are not from the mscorlib library, the type name returned by ToString might not be able to be parsed by Type.GetType(string) method.

György Kőszeg
  • 17,093
  • 6
  • 37
  • 65