GetType in a static method

E

Eric Le Guehennec

Hello,

I am trying to get the Type of a class in a static method.

Here is a sample of what I would like to do (c#):
private static void Dummy()
{
Type t = this.GetType()
}

Because it is a static method, the 'this' keyword isn't usable.

I know I could use GetType() from the name of the class, but it's not
possible in my case as I'd like to get the name of the child class
from a abstract parent class.

Is it possible ?

Thanks for your help
 
M

Miha Markic

Hi Eric,

Eric Le Guehennec said:
Hello,

I am trying to get the Type of a class in a static method.

Here is a sample of what I would like to do (c#):
private static void Dummy()
{
Type t = this.GetType()
}

Because it is a static method, the 'this' keyword isn't usable.

I know I could use GetType() from the name of the class, but it's not
possible in my case as I'd like to get the name of the child class
from a abstract parent class.

Is it possible ?

No, because static method has no clue of instances.
You might pass the instance reference to static method though.
 
J

Jon Skeet [C# MVP]

Eric Le Guehennec said:
I am trying to get the Type of a class in a static method.

Here is a sample of what I would like to do (c#):
private static void Dummy()
{
Type t = this.GetType()
}

Because it is a static method, the 'this' keyword isn't usable.

I know I could use GetType() from the name of the class, but it's not
possible in my case as I'd like to get the name of the child class
from a abstract parent class.

Is it possible ?

No - a call to Derived.StaticMethod ends up being compiled to
Base.StaticMethod anyway.
 
E

Eric Newton

I think there's the notion of "Caller" or "Activator"

for instance, in the System.Windows.Forms.TreeNode class, Clone method, the
author, ...very ingeniously i might add..., performs an
Activator.CreateInstance if the "instance of this" isn't a TreeNode, which
solves a problem that has plagued some of my object models, giving the
father of a class the ability to instantiate a derived instance without
directly knowing about the derived class.

Look into the Activator, it may yield what you need.
 

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