Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to I get the class name when I am passing in a generic in my method?

Tags:

c#

reflection

My method looks like:

public string DoObjectProperties<T>(T obj, string text) {  } 

Now from within the method, I need to get the string value of the class name that i pass into the method's 'obj' parameter.

So if I pass in the User object, I need the text 'user'.

To get the properties I am using: typeof(T).GetProperties()

How can I get the classes name?

like image 378
Blankman Avatar asked Mar 28 '10 22:03

Blankman


People also ask

How do I find my generic class name?

You can see that in the main method, or in any instance method, I am capable to get the name of the generics type, in this case the main will print: java. lang. Integer. ...and you get the name of the subclass (if any).

How do you define generic classes?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

Can generic class be inherited?

You cannot inherit a generic type. // class Derived20 : T {}// NO!

What is the difference between generic class and generic method?

A generic class or structure can contain nongeneric procedures, and a nongeneric class, structure, or module can contain generic procedures. A generic procedure can use its type parameters in its normal parameter list, in its return type if it has one, and in its procedure code.


1 Answers

Just use .Name like this:

typeof(T).Name 

This gives for example "String", there's also .FullName which would give "System.String"

like image 149
Nick Craver Avatar answered Oct 20 '22 01:10

Nick Craver