78

How to check programmatically if a type is a struct or a class?

2

8 Answers 8

103

Use Type.IsValueType:

Gets a value indicating whether the Type is a value type.

Use it either like this:

typeof(Foo).IsValueType

or at execution time like this:

fooInstance.GetType().IsValueType

Conversely there is also a Type.IsClass property (which should have been called IsReferenceType in my opinion but no matter) which may or may not be more appropriate for your uses based on what you are testing for.

Code always seems to read better without boolean negations, so use whichever helps the readability of your code.


As Stefan points out below, in order to properly identify structs you must be careful to avoid false positives when it comes to enums. An enum is a value type so the IsValueType property will return true for enums as well as structs.

So if you truly are looking for structs and not just value types in general you will need to do this:

Type fooType = fooInstance.GetType();
Boolean isStruct = fooType.IsValueType && !fooType.IsEnum;
Sign up to request clarification or add additional context in comments.

19 Comments

A primitive type is also a value type.
@Stephan - It is true that all C# primitives happen to be value types but that does not mean that all value types are therefore C# primitives. System.Guid and System.DateTime are both value types but are not language primitives.
To expand my point, the term "primitive" is special and really only is reserve for certain types that have overridden the IsPrimitiveImpl method from System.Type. There is nothing stopping Microsoft from implementing a new primitive that happens to be a reference type. There is nothing about a primitive that necessitates that it must also be a value type.
Correct, enums and structs are the two value types that C# supports. A helpful way to remember this is that a struct is a kind of value type, not the other way around.
I need to serialize some data and this method does not work as it thinks a float is a struct. I need to recursively serialize structs down to their primitives but some structs can have other structs as fields.
|
46
Type type = typeof(Foo);

bool isStruct = type.IsValueType && !type.IsPrimitive;
bool isClass = type.IsClass;

It could still be: a primitive type or an interface.


Edit: There is a lot of discussion about the definition of a struct. A struct and a value type are actually the same, so IsValueType is the correct answer. I usually had to know whether a type is a user defined struct, this means a type which is implemented using the keyword struct and not a primitive type. So I keep my answer for everyone who has the same problem then me.


Edit 2: According to the C# Reference, enums are not structs, while any other value type is. Therefore, the correct answer how to determine if a type is a struct is:

bool isStruct = type.IsValueType && !type.IsEnum;

IMHO, the definition of a struct is more confusing then logical. I actually doubt that this definition is of any relevance in praxis.

5 Comments

The primitive type thing has been discussed to death in the comments of my answer :) You don't have to worry about an interface because and interface type instance will return false for both IsClass and IsValueType. Also any type that implements the interface will return its true type regardless of what the reference to the type is typed as an interface or not.
@Stefan: Are you saying that primitive types are precluded from being structs? If so, you're incorrect. For example, section 11 of the C# spec says "the simple types provided by C#, such as int, double, and bool, are in fact all struct types".
@Luke: Yes, this is indeed the definition of primitive types. I always had to know if a type is a user defined struct, excluding primitive types, which is normally simply referenced to as "struct". But you are right, strictly speaking primitive types are also structs.
type.IsValueType && !type.IsPrimitive will not determine if the struct is a user-defined struct created using the keyword struct. It will return false positives for example for decimal, int?, or any enum.
@thepirat000: Yes. There is no concept of "user-defined struct" in C#. Decimals and nullables are structs like any other. Of course you can exclude them explicitly, if it makes sense. There is a related (but different!) question with a better answer here: stackoverflow.com/questions/863881/…
4

Extension method. It returns true for anything defined as a struct in my code but not for things like int which although they are technically structs are not for my purposes.

I needed to know when a type may have child fields or properties but was defined as a struct and not a class. Because when you alter a struct it just alters a copy, and then you have to set the original back to the altered copy to make the changes "stick".

public static bool IsStruct(this Type source) 
{
  return source.IsValueType && !source.IsPrimitive && !source.IsEnum;
}

1 Comment

Decimal is valuetype and not primitive (and not enum).
3

I think it would be something like this:

Is it a structure

public bool IsStructure(Type LocalType)
{
    bool result = false;
    if (LocalType.IsValueType)
    {
        //Is Value Type
        if (!LocalType.IsPrimitive)
        {
            /* Is not primitive. Remember that primitives are:
            Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32,
            Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single.
            This way, could still be Decimal, Date or Enum. */
            if (!LocalType == typeof(decimal))
            {
                //Is not Decimal
                if (!LocalType == typeof(DateTime))
                {
                    //Is not Date
                    if (!LocalType.IsEnum)
                    {
                        //Is not Enum. Consequently it is a structure.
                        result = true;
                    }
                }
            }
        }
    }
    return result;
}

Is it a Class

public bool IsClass(Type LocalType)
{
    bool result = false;
    if (LocalType.IsClass)
    {
        //Is Class or Delegate
        if (LocalType.GetType != typeof(Delegate))
            result = true;
    }
    return result;
}

2 Comments

Please provide some explanation.
1. Did you double post? Not only is this a bad piece of code, but it's here twice. 2. Use guard clauses. That nesting causes physical pain. 3. Use !=. Inversing an equals operation is also painful. 4. If we're chasing awkward exceptions, consider nullables, which aren't classes either.
1

Try the following

bool IsStruct(Type t) {
  return t.IsValueType;
}

1 Comment

See answer from @Stefan: type.IsValueType && !type.IsEnum
1

The struct:

// determine if the type is a struct..
var isStruct = type.IsValueType && !type.IsEnum &&
               !type.IsEquivalentTo(typeof(decimal)) && 
               !type.IsPrimitive;

The class:

var isClass = type.IsClass;

The answer:

var isClassOrStruct = isStruct | isClass;

Comments

0
    //I think it would be something like this:

    public sbyte IsStructure(Type LocalType)
    {
            sbyte result = false;
            if (LocalType.IsValueType)
            {
                    //Is Value Type
                    if (!LocalType.IsPrimitive)
                    {
                            /* Is not primitive. Remember that primitives are:
                            Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32,
                            Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single.
                            This way, could still be Decimal, Date or Enum. */
                            if (!LocalType == typeof(decimal))
                            {
                                    //Is not Decimal
                                    if (!LocalType == typeof(DateTime))
                                    {
                                            //Is not Date
                                            if (!LocalType.IsEnum)
                                            {
                                                    //Is not Enum. Consequently it is a structure.
                                                    result = true;
                                            }
                                    }
                            }
                    }
            }
            return result;
    }

Comments

-1

For every value type, there is a corresponding auto-generated class type which derives from System.ValueType, which in turn derives from System.Object. Note that value types themselves do not derive from anything, but are implicitly convertible to that class type, and instances of that class type may be explicitly converted to the value type.

Consider:

        public static int GetSomething<T>(T enumerator) where T : IEnumerator<int>
        {
            T enumerator2 = enumerator;
            enumerator.MoveNext();
            enumerator2.MoveNext();
            return enumerator2.Current;
        }

Calling this routine on a variable of type List<int>.Enumerator will yield very different behavior from calling it on a variable of type IEnumerator<int> which happens to have an instance of List<int>.Enumerator stored within it. Even though a variable of type List<int>.Enumerator is a value type, an instance of List<int>.Enumerator stored in a variable of type IEnumerator<int> will behave as a class type.

1 Comment

How is this answering the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.