GetType() in static method?

J

Jeff Dege

In a non-static method, I can obtain the Type of the class containing
that method with "this.GetType()".

In a static method, I cannot, of course. There is no "this".

I have a method in another class that needs to be passed a Type object
associated with a class. I'm calling that method from a static method,
and want to pass the Type object associated with the class that contains
that static method.

I can, of course, use "typeof(MyClass)". But that means redundancy of
the sort that just bothers me.
 
P

Peter Duniho

That is the only simple way.

And in fact is IMHO a perfectly reasonable way. The only reason to use
the this.GetType() in a method is to account for the possibility that the
method might be called by a derived type rather than the class in which
the method is defined.

But a static method doesn't have this risk. In the static method you
always know the type of the containing class, by definition. There'd be
absolutely no value in using any other reference to the type.

Pete
 
A

Arne Vajhøj

Jeff said:
In a non-static method, I can obtain the Type of the class containing
that method with "this.GetType()".

In a static method, I cannot, of course. There is no "this".

I have a method in another class that needs to be passed a Type object
associated with a class. I'm calling that method from a static method,
and want to pass the Type object associated with the class that contains
that static method.

I can, of course, use "typeof(MyClass)". But that means redundancy of
the sort that just bothers me.

MethodInfo.GetCurrentMethod().DeclaringType

but I would use probably use the typeof.

Arne
 
A

Arne Vajhøj

Peter said:
And in fact is IMHO a perfectly reasonable way. The only reason to use
the this.GetType() in a method is to account for the possibility that
the method might be called by a derived type rather than the class in
which the method is defined.

There is also the reason the original poster mentioned: avoiding
having to write the class name twice.

Arne
 
B

Ben Voigt [C++ MVP]

Arne Vajhøj said:
MethodInfo.GetCurrentMethod().DeclaringType

but I would use probably use the typeof.

Best of all worlds might be:

private static readonly Type ThisType = typeof(MyClass);

Now the particular class name only needs to be mentioned once, no matter how
many times it is needed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top