HelloWorld1
HelloWorld1

Reputation: 14108

In what context is it good to use the typeof operator?

I don't understand when to use the typeof() operator? In what context is it good to use it?

Upvotes: 0

Views: 122

Answers (3)

Manicguitarist
Manicguitarist

Reputation: 329

It is also used during .Net remoting when both Marshalling an object and also getting an object from an Activator.

When Marshalling an object you need to specify the interface the object exposes that you wish to marshal...

_pServerFileXFer = RemotingServices.Marshal(m_serverFileXFer, m_strURI, typeof(IServer));

And when getting an object from the remoting services...you need to specify what type of object you want to get:

IServer server = Activator.GetObject(typeof(IServer), m_txtURI.Text) as IServer;

Upvotes: 0

Robert Wagner
Robert Wagner

Reputation: 17793

It is like .GetType() except it works on a type name instead of an instance.

You would use typeof(MyType) if you need to get an instance of System.Type and you know the type at compile time. You don't need an instance of that type for resolve the description of that type (System.Type).

Eg if you had an instance you would:

object o = new MyType();
Type type = o.GetType()

But you could:

Type type = typeof(MyType)

Upvotes: 6

Daniel A. White
Daniel A. White

Reputation: 190935

It gets you an instance of Type from a type.

I can get the assembly of which this class is in.

typeof(MyClass).Assembly

Upvotes: 1

Related Questions