GetType() in static method?

  • Thread starter Thread starter Jeff Dege
  • Start date Start date
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.
 
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
 
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
 
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
 
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.
 
Back
Top