C#: .NET: Reflection

.NET Array Collections File String Async Cast DataTable DateTime Dictionary Enum Exception For Foreach IEnumerable If IndexOf Lambda LINQ List Parse Path Process Property Regex Replace Sort Split StringBuilder Substring Switch Tuple

Class shapes

The Assembly type contains many Type instances. In System.Reflection, we can use a static method such as GetCallingAssembly on the Assembly type.
And on Assembly,
we can get an array of types,
or a specific,
named type.

Static MethodType


This file includes the System.Reflection namespace. We call Assembly.GetCallingAssembly() to get the current assembly. And then with GetTypes, we receive an array of Type instances. We loop with foreach through these elements.

GetType:The GetType method next receives a string, and returns a Type pointer if one of that name is located.

C# program that uses Assembly type

using System;
using System.Reflection;

class Box

class Program
    static void Main()
	// Get assembly.
	Assembly assembly = Assembly.GetCallingAssembly();

	// Get array of types.
	Type[] types = assembly.GetTypes();
	foreach (Type t in types)

	// Get type by name.
	string name = "Box";
	Type type = assembly.GetType(name);



Programming tip

In this example, we use no custom namespaces. But if there were namespaces present, you would need to specify them in the argument to GetType—for example, "ConsoleApplication1.Box".

Tip:In this case, you could develop a custom search algorithm, with GetTypes() and IndexOf, to find types without their namespaces.



Assembly has many functions. It yields, with GetTypes, an array of all the types in the metadata. With its static methods, such as Assembly.GetCallingAssembly(), we access an Assembly instance.