Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 585
Jared Avatar asked Oct 07 '08 18:10

Jared


People also ask

How do I convert a class name to a string?

Get Class Name Using class. In the GetClassName class, we use ExampleClass. class to get the information of the class. It returns a Class instance of type ExampleClass . Now we can call getSimpleName() using the classNameInstance that will return only the class name as a String.

What is std:: string*?

C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

What is string class in C#?

In C#, a string is a sequence of Unicode characters or array of characters. The range of Unicode characters will be U+0000 to U+FFFF. The array of characters is also termed as the text. So the string is the representation of the text. A string is represented by a class System.


1 Answers

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 
like image 97
Max Schmeling Avatar answered Sep 28 '22 04:09

Max Schmeling