Java class name versus C #
In Java, I can just 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 the fully qualified class name "this.that.OneClass".
I tried the same in C # but got the error that I am using OneClass as a 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
}
Please note that I don't want to use an instance of the class
source to share
First, let's fix the Java code: this call
System.out.println(MyClass.toString(OneClass));
won't compile unless you add .class
in OneClass
:
System.out.println(MyClass.toString(OneClass.class));
The equivalent construct for syntax .class
in C # is typeof
. It takes a type name and creates an appropriate object System.Type
:
Console.WriteLine(MyClass.ToString(typeof(OneClass)));
Also, C # does not allow *this
as an identifier, so you must rename the namespace to exclude the keyword. Finally, it will print the unqualified class name. If you want to see the name in the namespace use the property :Name
FullName
public static String ToString(Type classType) {
return classType.FullName;
}
* The language allows you to use this
it if you prefix it @
, but you need to do your best to avoid using this trick.
source to share
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 for class packages
namespace outerscope.innerscope
{
public class OneClass
{
}
}
To print the full name
Console.WriteLine(MyClass.toString(typeof(outerscope.innerscope.OneClass)));
source to share