Skip to content

Instantly share code, notes, and snippets.

@jonathanconway
Created August 12, 2012 08:09
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jonathanconway/3330614 to your computer and use it in GitHub Desktop.
Save jonathanconway/3330614 to your computer and use it in GitHub Desktop.
Determine whether a type is simple.
public static class TypeExtensions
{
/// <summary>
/// Determine whether a type is simple (String, Decimal, DateTime, etc)
/// or complex (i.e. custom class with public properties and methods).
/// </summary>
/// <see cref="http://stackoverflow.com/questions/2442534/how-to-test-if-type-is-primitive"/>
public static bool IsSimpleType(
this Type type)
{
return
type.IsValueType ||
type.IsPrimitive ||
new Type[] {
typeof(String),
typeof(Decimal),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
typeof(Guid)
}.Contains(type) ||
Convert.GetTypeCode(type) != TypeCode.Object;
}
}
@JuanjoFuchs
Copy link

Very useful, thanks!

@odises
Copy link

odises commented Jul 5, 2013

Very useful, thanks bro!

@congdanhqx-zz
Copy link

I think Decimal, DateTime, DateTimeOffset, TimeSpan, Guid are ValueType. Not necessary to mention them later.

@D-Bullock
Copy link

This is great, thanks!

@ZiadJ
Copy link

ZiadJ commented Jul 10, 2014

That seems to do the job for me:

public static bool IsPrimitiveType(Type type)
{
    return (type == typeof(object) || Type.GetTypeCode(type) != TypeCode.Object);
}

I found it on the same page on stackoverflow by the way. It has less overhead and is way simpler.

@gsscoder
Copy link

Thanks, you avoided me to write one...

@dedo1911
Copy link

Thanks! Very useful

@hschachn
Copy link

Thank you!

@M3mbrillo
Copy link

Thank!!!

@goforgold
Copy link

IsValueType returns true for Collections which I don't want. I just removed it from your condition and used it.

@gabbsmo
Copy link

gabbsmo commented Apr 27, 2023

That seems to do the job for me:

public static bool IsPrimitiveType(Type type)
{
    return (type == typeof(object) || Type.GetTypeCode(type) != TypeCode.Object);
}

I found it on the same page on stackoverflow by the way. It has less overhead and is way simpler.

This variant will not return true for Guid, DateTimeOffset and possibly others.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment