Fetching the name of a class

V

vector

There's got to be a better way to do this.

In this sample code, I've created a class in a namespace, and a class
inside of a class. On calling .ToString() for those two classes, I
see different output:

name of Class1 is: ConsoleApplication1.Class1
name of Class2 is: ConsoleApplication1.CMain+Class2

I'm not interested in the hierarchical name of the class. All I
really want from it is "Class1" and "Class2". I could do some string
manipulation, for instance scanning from right to left for non-alpha
and non-numeric characters, but I'd like to think there's a more
intelligent way to derive only what I want without resorting to stupid
string tricks.

Can someone point me in the right direction?

using System;

namespace ConsoleApplication1
{
class Class1{}

class CMain
{
class Class2{}

static private string GetObjectName(object obj)
{
return obj.ToString(); //ugly. fix this.
}

[STAThread]
static void Main(string[] args)
{
Console.WriteLine("name of Class1 is: {0}", GetObjectName(new
Class1()));
Console.WriteLine("name of Class2 is: {0}", GetObjectName(new
Class2()));

Console.WriteLine();
Console.ReadLine();
}
}
}
 
N

Nicholas Paldino [.NET/C# MVP]

vector,

The ToString method is not guaranteed to give you the class name when
you call it, so you should not be using it.

You should use in your GetObjectName method "obj.GetType().Name".

Hope this helps.
 

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