There is a small, but important, difference between .Net Framework and .Net Core in how the Type.GetType method works that is going to catch some people out.
In .Net Framework, if the assembly containing the type is not loaded, Type.GetType will load it. In .Net Core it will not. We can demonstrate this quite easily.
Start a new C# .Net Core project in Visual Studio and call it GetType. Rename the project to GetTypeCore. Make program.cs look like this.
class Program
{
static void Main(string[] args)
Type t = Type.GetType("GetMe.MyType,GetMe");
}
}
Add a .Net Framework project called GetTypeFramework. Make program.cs look like this.
class Program
{
static void Main(string[] args)
Type t = Type.GetType("GetMe.MyType,GetMe");
}
}
Add a .Net Framework project called GetMe and rename Class1 to MyType. It doesn't need any code.
Make GetTypeFramework the startup project and run it. You will see the expected output.
Now make GetTypeCore the startup project and run it. You will get an error because GetType returns null.
You need to explicitly load the assembly before you can use GetType on it. Change GetTypeCore's program.cs to this (changing the path as appropriate).
class Program
{
static void Main(string[] args)
Assembly a = Assembly.LoadFrom(@"C:\Users\me\source\repos\GetType\GetMe\bin\Debug\GetMe.dll");
}
}
Now it works.
No comments:
Post a Comment