-1

My function gets enum types as strings which I need to validate.

Why do the parsedType(s) are null here?

var parsedType1 = Type.GetType("System.Windows.TextAlignment.Left");
var parsedType2 = Type.GetType("System.Windows.TextAlignment");

though this works?

var parsedType3 = Type.GetType("System.String");
marsh-wiggle
  • 2,508
  • 3
  • 35
  • 52

1 Answers1

8

The first line would fail because System.Windows.TextAlignment.Left isn't the name of a type - it's the name of a field within a type.

The second line would fail because when you provide Type.GetType(string) with just a type name, without any assembly part, it looks in the currently executing assembly and mscorlib. That's why "System.String" works.

If you know which assembly the type will be in, just use Assembly.GetType(string) instead.

For example:

// Here TextDataFormat is just another type that's in the same assembly
Type textAlignment = typeof(TextDataFormat).Assembly.GetType("System.Windows.TextAlignment");

Or you could specify the assembly name in the string:

Type textAlignment = Type.GetType("System.Windows.TextAlignment, PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194