I can create a new class with a fully qualified name like Namespace.OuterClass.NestedClass
. But attempting to get the type with Type.GetType("Namespace.OuterClass.NestedClass")
returns null
. Here is sample code:
namespace Sample
{
public class Program
{
public class Animal { }
public class Vegetable { }
public class Mineral { }
static public void Test()
{
Object o = new Sample.Program.Vegetable();
Type t = Type.GetType("Sample.Program.Vegetable"); // returns null
Console.ReadKey();
}
static void Main(string[] args)
{
Program.Test();
}
}
}
How can I use Type.GetType
for a nested class?
GetType(String, Boolean, Boolean) Gets the Type object with the specified name in the assembly instance, with the options of ignoring the case, and of throwing an exception if the type is not found.
To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. GetType with the assembly qualified type name will look for the Type in any assembly.
As a member of the OuterClass , a nested class can be declared private , public , protected , or package private.
There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes. A class created within class and outside method. A class created for implementing an interface or extending class.
String values for C# fully qualified names use +
between classes. Get the type by string with Type.GetType("Namespace.OuterClass+NestedClass")
.
MSDN documentation for Type.GetType(string)
gives a syntax table for various types (generic types, arguments, unmanaged pointers, etc.) including "parent class and a nested class".
Adding these lines to the question's sample code:
string typeName1 = typeof(Sample.Program.Vegetable).FullName;
string typeName2 = typeof(Vegetable).FullName;
will prove the string type name equal to Sample.Program+Vegetable
ECMA-335 Partition IV's associated CLILibrary.xml provides the definitive details for this convention. The Type.GetType(string)
syntax table in ECMA-335 is identical to that used in the MSDN documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With