typeof

  • Thread starter Thread starter Peter Kirk
  • Start date Start date
P

Peter Kirk

Hi

is there a difference between "this.GetType()" and typeof(MyClass)?

The only reason I ask is that we are using log4net in a project, and we give
the Loggers names based on the class name.

For example, some people use:
ILog log = LogManager.GetLogger(typeof(Finder).ToString());
others use:
ILog log = LogManager.GetLogger(this.GetType().ToString());

Is there any difference?

Thanks,
Peter
 
Peter said:
Hi

is there a difference between "this.GetType()" and typeof(MyClass)?

this.GetType() is virtual, and will give you the type of this instance.
typeof(MyClass) is static and will give you the type of MyClass.

The difference is apparent here:

class Bar {
string TestType() {
return string.format("this.GetType()={0}, typeof(Bar)={1}",
this.GetType(), typeof(Bar)); }
}
class Foo: Bar {}

Console.Writeline(new Foo().TestType());
For example, some people use:
ILog log = LogManager.GetLogger(typeof(Finder).ToString());
others use:
ILog log = LogManager.GetLogger(this.GetType().ToString());

Is there any difference?

Yes, and even worse... it is significant, since typeof() and GetType()
will put log-messages from Foo in different loggers.

BTW: You cannot argue which method is "best" in general for your
purpose, both would probably have their valid uses.
 
Helge Jensen said:
class Bar {
string TestType() {
return string.format("this.GetType()={0}, typeof(Bar)={1}",
this.GetType(), typeof(Bar)); }
}
class Foo: Bar {}

Console.Writeline(new Foo().TestType());


Yes, and even worse... it is significant, since typeof() and GetType()
will put log-messages from Foo in different loggers.

BTW: You cannot argue which method is "best" in general for your purpose,
both would probably have their valid uses.

OK, I can see arguments for both sides.

With respect to log4net, then, what are good, consistent naming conventions
for loggers?
 
GetType tells the type of a particular instance of a class. typeof() uses
reflection to look at the actual underlying type. From the standpoint of the
code, the main difference is whether or not you are looking at an instance of
a class to determine the logger or you are working without an instance and
creating one based on a specific type.

Hope this helps.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

***************************
Think Outside the Box!
***************************
 
Back
Top