Get Type from a class without instantiating it

1

I need to get the Type of a class without instantiating it, I tried to do this:

variavelQualquer.Type = new ClasseA().Type; // Type é uma variável pública que guarda o valor do método GetType()

But so an instance is still created (seen as it was done, it is the same expected). How to get the class type without this happening? Is it possible?

    
asked by anonymous 18.07.2015 / 02:44

1 answer

2

In general it does not make much sense to want to know the type of a class, after all the type of this class is the class itself. At least it makes no sense to get this in the example shown. That is, the type of class ClasseA is ClasseA . It's obvious in the code.

If you are in a situation where it is not so obvious, using reflection, for example, you have some alternatives.

You can use the typeof operator that is resolved at compile time:

Type t = typeof(Ns.Classe);

You can use the method GetType() in the type without create an instance. Just take care of using the full type name with namespace (resolved at runtime):

Type t = Type.GetType("Ns.Classe");

See running on dotNetFiddle .

    
18.07.2015 / 03:16