Reputation: 4325
I am using someone's SDK, but the document does not tell me something is a struct or a class.
How can I find out that? typeof
or GetType
just show the name.
I'd like find out that in the IDE(VS2010); approaches through coding are also acceptable.
Upvotes: 3
Views: 147
Reputation: 81159
As mentioned, you can find out whether a generic type is a class type or value type by calling IsValueType
on the type object. Note, however, that it's not meaningful to test whether an object instance is a value type. Although C# will pretend that a reference-type fields can hold a value-type instance, that's an illusion. For every value type there is a corresponding class type with the same name and fields. Calling GetType().IsValueType
on a storage location holding a reference to such an instance will report true, even though the storage location in fact holds a reference to a class object. This can be demonstrated readily with structs that implement mutating interfaces (e.g. List<string>.Enumerator
, which I'll call LSE
for short).
An LSE
which is stored in a variable of type LSE
will behave as a value type. Copying an LSE
which is about to return the third item of a list to another variable of type LSE
will yield a second, independent enumerator, which is also about to return the third item. One can read items from either enumerator without affecting the other. By contrast, if one has a variable of type IEnumerable<string>
which holds a reference to an LSE
, and one copies that to another variable of type IEnumerable<string>
, one will have a second reference to the same enumerator. Reading items from one enumerator will also advance the other. In other words, copying an LSE
to a reference-type storage location will yield something which will behave like a reference type because, under the covers, it will actually be one.
Note that calling GetType
on a storage location won't reveal whether it holds a real value type, or whether it holds an object of the class associated with a value type. In the former case, the system will create a new instance of the class associated with the value type and call GetType
on that, so in both cases the GetType
call will actually be processed on a class-type instance.
Upvotes: -1
Reputation: 27339
Programmatically speaking, you can use GetType().IsValueType
.
From Visual Studio, you can also check by using the Object Browser (shown below, found under View -> Object Browser).
Upvotes: 7