Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetType from object is returning RuntimeType [duplicate]

Tags:

c#

I have a simple function:

public string getType(object obj) {
    Type type = obj.getType();
    return type.FullName;
}

If you use this function on a string object, which was created on runtime, the function returns "System.RuntimeType"...

But it should return "System.String"...

like image 436
bitwave Avatar asked Oct 21 '12 12:10

bitwave


People also ask

What does GetType() do?

The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.

What is runtimeType?

What is runtimeType Property ? The runtimeType property is used to find out the runtime type of the object. The keyword var in Dart language lets a variable store any type of data. The runtimeType property helps to find what kind of data is stored in the variable using var keyword.

How do you find out if the object is of specific type or not?

In summary: If you only need to know whether or not an object is of some type, use is . If you need to treat an object as an instance of a certain type, but you don't know for sure that the object will be of that type, use as and check for null .


2 Answers

If you call it like this -

string a = "";
string type = getType(a);

It will return System.String

But if you call like this -

string a = "";
string type = getType(a.GetType());

Then it will return System.RuntimeType

Also, there is small typo in your method -

Type type = obj.getType(); should be Type type = obj.GetType();

like image 136
Rohit Vats Avatar answered Oct 19 '22 04:10

Rohit Vats


I guess you called it like this: getType(typeof(string)). typeof(abc) is a value of type Type (or RuntimeType which is an implementation detail).

Call it like this:

getType("")

like image 24
usr Avatar answered Oct 19 '22 03:10

usr