what is "Type" use for in C#?

兰树豪 381 Reputation points
2023-03-19T17:26:56.22+00:00

let's say we have a unknow type instance_X, we get it's type:

Type typeA = instance_X.GetType();

How do I use this variable typeA?

Can it be used to declare a variable or instantiate an object?

like: typeA typeaa = new typeA(); // if typeA is a class tpye

 or  typeA  typeaa ;    // if typeA is a int or bool or string......

It doesn't seem to work。

Developer technologies Windows Presentation Foundation
Developer technologies .NET Other
Developer technologies Visual Studio Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,676 Reputation points Microsoft External Staff
    2023-03-20T03:00:36.52+00:00

    Hi,@兰树豪. Welcome Microsoft Q&A.

    Type Class represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.

    Type is the root of the System.Reflection functionality and is the primary way to access metadata. Use the members of Type to get information about a type declaration, about the members of a type (such as the constructors, methods, fields, properties, and events of a class), as well as the module and the assembly in which the class is deployed.

    You could see Remarks for more information.

    It cannot be directly declared a variable or instantiate an object.

    If you use the code typeA typeaa = new typeA(); it will produce an error CS0118 'typeA' is a variable but is used like a type.

    As Peter said, you could use Activator.CreateInstance Method .

    The CreateInstance<T>() generic method is used by compilers to implement the instantiation of types specified by type parameters.

    object typeaa  = Activator.CreateInstance(typeA);
    

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,341 Reputation points
    2023-03-19T18:46:17.94+00:00

    Hi,
    you can use Activater from System namespace like in this demo:

    			internal void Execute()
    			{
    				Data d1 = new Data();
    				Type typeA = d1.GetType();
    				Console.WriteLine(typeA.ToString());
    				object d2 = Activator.CreateInstance(typeA);
    				Console.WriteLine(d2.ToString());
    			}
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.