Get the name of a class as a string in C#


Question

Is there a way to take a class name and convert it to a string in C#?

As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be able to have compile-time safety when referencing this class.

Thus, is there a way that I could do this:

class Foo
{
}

tblBar.Include ( Foo.GetType().ToString() );

I don't think I can do GetType() without an instance. Any ideas?

1
65
10/7/2008 6:14:46 PM

Accepted Answer

Include requires a property name, not a class name. Hence, it's the name of the property you want, not the name of its type. You can get that with reflection.

12
10/7/2008 6:21:19 PM

You can't use .GetType() without an instance because GetType is a method.

You can get the name from the type though like this:

typeof(Foo).Name

And as pointed out by Chris, if you need the assembly qualified name you can use

typeof(Foo).AssemblyQualifiedName

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon