How to check programmatically if a type is a struct or a class?
How to check programmatically if a type is a struct or a class?
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;
}
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;
//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;
}