Home > Backend Development > C++ > How to Determine Object Type from its String Representation in C#?

How to Determine Object Type from its String Representation in C#?

Mary-Kate Olsen
Release: 2025-01-23 14:47:13
Original
198 people have browsed it

Determine object type based on string representation in C#

In C#, a string containing a type name can be converted into the corresponding Type object. However, the method used for this conversion depends on whether the type is defined in the same assembly as the calling code, or in a different assembly.

Use Type.GetType(string)

If the type is defined in the same assembly, you can use the Type.GetType(string) method and provide the fully qualified type name as a string. For example, to get the int of the Type data type, you would use:

<code class="language-csharp">Type.GetType("System.Int32");</code>
Copy after login

Use Assembly.GetType(string)

If the type is defined in a different assembly, you also need to provide the assembly name. This can be achieved using the Assembly.GetType(string) method. First, get a reference to the assembly, then use that reference to get the Type:

<code class="language-csharp">Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType("Namespace.MyClass");</code>
Copy after login

Namespace and assembly qualification

Make sure to include the type's namespace in the string provided to Type.GetType() or Assembly.GetType(). Additionally, for strong-named assemblies, it may be necessary to include the full assembly identity, including version, culture, and public key tags.

Example scenario

Consider the following scenario, where there is a string containing the fully qualified name of a type:

<code class="language-csharp">string typeName = "Namespace.MyClass, MyAssembly";</code>
Copy after login

Depending on whether MyAssembly is referenced by the calling assembly, either Type.GetType() or Assembly.GetType() can be used:

<code class="language-csharp">// 如果 MyAssembly 被引用
Type type1 = Type.GetType(typeName);

// 如果 MyAssembly 未被引用
Assembly asm = typeof(SomeKnownType).Assembly;
Type type2 = asm.GetType(typeName);</code>
Copy after login

How to Determine Object Type from its String Representation in C#?

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template