Home > OS >  Type T = Type.GetType(TypeName); T is returning Null
Type T = Type.GetType(TypeName); T is returning Null

Time:02-06

Its a simple program where I am passing System.Console and it will return me the Methods it has by using Reflection ... Here Type object T is taking Null even after I am passing System.Console in txtTypeName.Text

My Code :

    string TypeName = txtTypeName.Text;
    Type T  = Type.GetType(TypeName,true);

    MethodInfo[] methods = T.GetMethods();
    foreach (MethodInfo method in methods)
    {
        lstMethod.Items.Add(method.Name);
    }

Type T = Type.GetType(TypeName); T is returning Null

CodePudding user response:

The behaviour of Type.GetType() has changed for .net Core and later.

This code works with .net 4.8:

Type? t = Type.GetType("System.Console", true);
Console.WriteLine(t!.FullName);

But it fails in .net Core and later!

Repro showing it not working in .net 6.0: https://dotnetfiddle.net/JlAhqn

Repro showing it working in .net 4.7.2: https://dotnetfiddle.net/ahV7fC

To make this work in .net Core or later you need to specify the assembly-qualified name of the type, which includes the name of the assembly from which this Type object was loaded.

For the type System.Console the assembly name is also "System.Console" so the following works in .net Core and .net Framework:

Type? t = Type.GetType("System.Console, System.Console", true);
Console.WriteLine(t!.FullName);

Repro showing it working in .net 6.0: https://dotnetfiddle.net/dA1ulx

CodePudding user response:

The accepted answer is not quite correct.

The behaviour of Type.GetType did not change between framework versions. The documentation in both of them states (my bold):

Parameters

typeName String

The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, it is sufficient to supply the type name qualified by its namespace.

Only types that are in the calling assembly or in the BCL assembly do not need qualification. The difference between the two version of the framework is simply that System.Console got moved to a different assembly, so that is why it is failing. The docs for .NET 6 shows System.Console.dll, while NET 4.7 shows mscorlib.dll

You can, for example, see in these two fiddles what happens if you try System.DateTime without qualification: it works in both cases.
.NET 4.7
.NET 6

  •  Tags:  
  • Related