Home >Backend Development >C++ >How to Convert a String to a Type Object in C#?

How to Convert a String to a Type Object in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-23 14:26:09587browse

How to Convert a String to a Type Object in C#?

Convert string to type object in C#

Convert the string representation of a type to its corresponding Type object, which can be achieved through the Type.GetType() method. This method accepts a string parameter that represents the assembly-qualified type name.

By default, Type.GetType() only searches the mscorlib assembly and the calling assembly for the specified type. If your custom type is defined in a referenced assembly, you must provide the complete assembly-qualified type name, including the assembly name.

For example:

<code class="language-csharp">Type type = Type.GetType("Namespace.MyClass, MyAssembly");</code>

If your assembly is strongly named, you must also include that information in the type name string.

As an alternative, if you have a reference to the assembly containing the type, you can use the Assembly.GetType() method:

<code class="language-csharp">Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType(namespaceQualifiedTypeName);</code>

This method is useful when the type name is not known in advance. By specifying an assembly with a known class' type, you can retrieve a Type object for a specified type name.

The above is the detailed content of How to Convert a String to a Type Object in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn