Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get type of nested class with Type.GetType(string)

Tags:

syntax

c#

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?

like image 338
jltrem Avatar asked Sep 27 '13 15:09

jltrem


People also ask

How to Get Type of assembly in c#?

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.

How to use type GetType?

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.

What are the four types of nested classes?

As a member of the OuterClass , a nested class can be declared private , public , protected , or package private.

What are the types of nested classes?

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.


1 Answers

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.

like image 182
jltrem Avatar answered Nov 03 '22 00:11

jltrem