David S.
David S.

Reputation: 6105

Does t.GetType() return the same Type instance?

I'm thinking about storing a Type variable in my objects. However, there can be quite a lot of them, but the amount of different types is not so large. I'm worried about using a lot of memory to store the Type in all those objects, when the type could be the same for many of them.

Is a new instance of Type created every time I look up the type of something, with either t.GetType() or typeof(T)? Or is it actually the same? If it was the same I wouldn't have to worry about the memory.

Note that I have considered generics, which is not an alternative in this case.

Upvotes: 2

Views: 768

Answers (2)

CodeCaster
CodeCaster

Reputation: 151594

MSDN: Object.GetType Method:

For two objects x and y that have identical runtime types, Object.ReferenceEquals(x.GetType(),y.GetType()) returns true.

So, yes.

Upvotes: 13

JLRishe
JLRishe

Reputation: 101672

There is only one instance for each type. If you evaluate:

"hello".GetType() == typeof(String)

or

Object.ReferenceEquals("hello".GetType(), typeof(String))

You will get the value true.

This works with generics as well:

Dictionary<string, string> dict = new Dictionary<string, string>();
// same will have the value true
bool same = Object.ReferenceEquals(dict.GetType(), typeof(Dictionary<string, string>));

Upvotes: 4

Related Questions