WonderMouse
WonderMouse

Reputation: 45

Java vs. C# class name

In Java, I can simply have class names like this:

public class MyClass
{
    public static String toString(Class<?> classType)
    {
        return classType.getName() ;
    }
}

package this.that;
public class OneClass
{
}

public static void main()
{
   System.out.println(MyClass.toString(OneClass));
}

to return me full class name "this.that.OneClass".

I tried same in C#, but got error that i'm using OneClass as type.

public class MyClass
{
    public static String ToString(Type classType)
    {
        return classType.Name ;
    }
}

namespace this.that
{
    public class OneClass
    {
    }
}

static Main()
{
    Console.WriteLine(MyClass.ToString(OneClass));  // expecting "this.that.OneClass" result
}

Note that I don't want to use class instance

Upvotes: 3

Views: 286

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

First, let's fix your Java code: this call

System.out.println(MyClass.toString(OneClass));

would not compile unless you add .class to OneClass:

System.out.println(MyClass.toString(OneClass.class));

The equivalent construct to .class syntax in C# is typeof. It takes a type name, and produces the corresponding System.Type object:

Console.WriteLine(MyClass.ToString(typeof(OneClass)));

In addition, C# does not allow this as an identifier*, so you should rename the namespace to exclude the keyword. Finally, Name will print the unqualified name of the class. If you would like to see the name with the namespace, use FullName property:

public static String ToString(Type classType) {
    return classType.FullName;
}

Demo.

* The language allows you to use this if you prefix it with @, but one should make every effort to avoid using this trick.

Upvotes: 10

Michal L&#237;ska
Michal L&#237;ska

Reputation: 36

In C# you of course must use typeof(OneClass) as others suggested.

But your toString method is also wrong, you have to use Type.FullName to get namespace, not just Type.Name

Upvotes: 0

Suresh Kumar Veluswamy
Suresh Kumar Veluswamy

Reputation: 4363

You need to use namespaces instead of packages in c#

public class MyClass
{
    public static String toString(Type classType)
    {
        // returns the full name of the class including namespace
        return classType.FullName;
    }
}

you can use namespace to package classes

namespace outerscope.innerscope
{
    public class OneClass
    {
    }
}

To print the full name

Console.WriteLine(MyClass.toString(typeof(outerscope.innerscope.OneClass)));

Upvotes: 0

David Arno
David Arno

Reputation: 43264

The line:

Console.WriteLine(MyClass.ToString(OneClass));

isn't valid C#. You need to do:

Console.WriteLine(MyClass.ToString(typeof(OneClass)));

Upvotes: 0

Related Questions