Nime Cloud
Nime Cloud

Reputation: 6395

typeof & GetType

I serialize a class below and the method needs object type as parameter.

string xml = SerializeObject(data, typeof(ClassData));

I think second parameter is not necessary. How can I remove the second parameter? How can I get type of data as Type ?

Upvotes: 1

Views: 2016

Answers (5)

Mikael Östberg
Mikael Östberg

Reputation: 17156

You can do:

data.GetType()

which would give you the type of data

The entire expression would be

string xml = SerializeObject(data, data.GetType());

GetType() is a method that is declared on Object and can be used on an instance of an object.

typeof() is a statement that can be used on a Type without having an instance of it.

// Get type from instance
Type type = data.GetType()

// Get type from Type
Type type = typeof(ClassData)

Upvotes: 6

Bala R
Bala R

Reputation: 108957

string xml = SerializeObject(data, data.GetType());

if you have

Person p = ... ;

to get the type, you can do

Type t = p.GetType()

if you need the runtime type of the object. p could be an object of a class that extends Person.

or

Type t = typeof(Person);

Upvotes: 2

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

To get the type of data as Type, you can use this syntax:

Type dataType = data.GetType();

I hope that is what you are asking, as the question is not entirely clear to me.

Upvotes: 1

Joachim VR
Joachim VR

Reputation: 2340

data.GetType() should return the type object of the class of 'data'.

Upvotes: 1

Nick
Nick

Reputation: 25799

Use the following:

classData.GetType( );

Upvotes: 1

Related Questions