Alireza
Alireza

Reputation: 10476

Type-safely pass a class name to a method

I need the class name in a method say for example X. Meanwhile, I don't want to loose type-safety and I'm not gonna allow other developers to pass a string (class name) to the method.

Something like this:

void X( ??? class) // --> don't know how
{
 var className = get the name of class // --> which I don't know how
 Console.WriteLine(className);
}

X(tblEmployee); //--> usage of X, where tblEmployee is a POCO class

Upvotes: 5

Views: 2866

Answers (3)

Rotem
Rotem

Reputation: 21917

What you are looking for is a called a Type, which contains metadata about classes.

You can use the typeof(class) or .GetType() method on any object instance.

The different is that typeof is resolved statically and GetType is resolved at runtime.

void X(Type type)
{
    Console.WriteLine(type.FullName);
}

X(typeof(tblEmployee));

Upvotes: 15

Gaurav
Gaurav

Reputation: 221

void X(Type type)
{
    if(type == typeof(DesiredType))
    {
          Do Some Action
    }
}

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

You could use generics and the FullName property of Type, as such:

void WriteClassName<TClass>(TClass item)
  where TClass : class {
    Console.WriteLine(item.GetType().FullName);
}

And then apply contraints on TClass as per your requirements.

Upvotes: 7

Related Questions