Get Type from a class without instantiating it

Asked

Viewed 59 times

1

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

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

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

1 answer

2


In general it does not make much sense you 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 class type ClasseA is ClasseA. It’s obvious in the code.

If you’re in a situation where it’s not so obvious, using reflection, for example, has some alternatives.

Can be using the operator typeof which is solved at compilation time:

Type t = typeof(Ns.Classe);

You can use the method GetType() type without creating an instance. Just be careful to use the full name of the type with the namespace (solved at runtime):

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

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.