The string is probably a special case.
I think I will do .....
bool IsSimple(Type type) { return type.IsPrimitive || type.Equals(typeof(string))); }
Edit:
Sometimes you need to cover a few more cases, such as enumerations and decimal numbers. Enumerations are a special type of type in C #. Decimal numbers are structures like any other. The problem with structures is that they can be complex, they can be user-defined types, they can be just a number. Thus, you have no other chance than knowing what they should distinguish.
bool IsSimple(Type type) { return type.IsPrimitive || type.IsEnum || type.Equals(typeof(string)) || type.Equals(typeof(decimal)); }
Handling zero-matching equivalents is also a bit complicated. Zero-value itself is a structure.
bool IsSimple(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { // nullable type, check if the nested type is simple. return IsSimple(type.GetGenericArguments()[0]); } return type.IsPrimitive || type.IsEnum || type.Equals(typeof(string)) || type.Equals(typeof(decimal)); }
Test:
Assert.IsTrue(IsSimple(typeof(string))); Assert.IsTrue(IsSimple(typeof(int))); Assert.IsTrue(IsSimple(typeof(decimal))); Assert.IsTrue(IsSimple(typeof(float))); Assert.IsTrue(IsSimple(typeof(StringComparison))); // enum Assert.IsTrue(IsSimple(typeof(int?))); Assert.IsTrue(IsSimple(typeof(decimal?))); Assert.IsTrue(IsSimple(typeof(StringComparison?))); Assert.IsFalse(IsSimple(typeof(object))); Assert.IsFalse(IsSimple(typeof(Point))); // struct in System.Drawing Assert.IsFalse(IsSimple(typeof(Point?))); Assert.IsFalse(IsSimple(typeof(StringBuilder))); // reference type
Stefan Steinegger May 14 '09 at 15:14 2009-05-14 15:14
source share