How do I tell if a type is a simple type? i.e. holds a single value
String is probably a special case.
I think I would do.....
bool IsSimple(Type type)
{
return type.IsPrimitive
|| type.Equals(typeof(string));
}
Edit:
Sometimes you need to cover some more cases, like enums and decimals. Enums are a special kind of type in C#. Decimals are structs like any other. The problem with the structs is that they may be complex, they may be user defined types, they may be just a number. So you don't have any other chance than knowing them to differentiate.
bool IsSimple(Type type)
{
return type.IsPrimitive
|| type.IsEnum
|| type.Equals(typeof(string))
|| type.Equals(typeof(decimal));
}
Handling nullable counterparts are also a bit tricky. The nullable itself is a struct.
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
Note to .NET Core
As DucoJ points out in his answer, some of the used methods are not available on the class Type
in .NET core anymore.
Fixed code (I hope it works, I couldn't try myself. Otherwise please comment):
bool IsSimple(Type type)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// nullable type, check if the nested type is simple.
return IsSimple(typeInfo.GetGenericArguments()[0]);
}
return typeInfo.IsPrimitive
|| typeInfo.IsEnum
|| type.Equals(typeof(string))
|| type.Equals(typeof(decimal));
}
how does a class as a data type or return type works. Can some one please tell,
Think of a class as a custom datatype.
We have strings, which represent words.
We have ints, which represent whole numbers.
There is no native datatype for Node, which you want to have a data and next property.
As you pass the Node class like you would any other datatype, but will have information on the Node data and Node next, not just a string or int.
How to check programmatically if a type is a struct or a class?
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;
WCF: For which property type do I have to call SetLink
I ended up with the following solution. I found a hint in the qestion of Nathan Ridley:
/// <summary>
/// Helper class for analyzing a type.
/// </summary>
public static class TypeAnalyzer
{
/// <summary>
/// Calculates if the given type is a "simple" type.
/// </summary>
/// <param name="type">Type to be checked for simplicity.</param>
/// <returns>True, if the type is "simple";false otherwise.</returns>
/// <remarks>
/// The following types are assumed to be simple:
/// <list type="*">
/// <item>string</item>
/// <item>int</item>
/// <item>decimal</item>
/// <item>float</item>
/// <item><see cref="StringComparison"/> (enum type)</item>
/// <item>int? (nullable simple types)</item>
/// </list>
/// The following types are not simple:
/// <list type="*">
/// <item>Point (struct)</item>
/// <item>Point? (nullable struct)</item>
/// <item>StringBuilder (class)</item>
/// </list>
/// </remarks>
public static bool IsSimple(this Type type)
{
if (IsNullableType(type))
return IsNestedTypeSimple(type);
return type.IsPrimitive
|| type.IsEnum
|| type.Equals(typeof(string))
|| type.Equals(typeof(decimal))
|| type.Equals(typeof(DateTime))
|| type.Equals(typeof(Guid));
}
private static bool IsNestedTypeSimple(Type type)
{
var nestedType = Nullable.GetUnderlyingType(type);
return IsSimple(nestedType);
}
private static bool IsNullableType(Type type)
{
return Nullable.GetUnderlyingType(type) != null;
}
}
Test cases written in NUnit are:
[TestFixture]
public class TypeAnalyzerTests
{
[TestCase(typeof(string), true)]
[TestCase(typeof(int), true)]
[TestCase(typeof(decimal), true)]
[TestCase(typeof(float), true)]
[TestCase(typeof(StringComparison), true)]
[TestCase(typeof(int?), true)]
[TestCase(typeof(decimal?), true)]
[TestCase(typeof(StringComparison?), true)]
[TestCase(typeof(object), false)]
[TestCase(typeof(Point), false)]
[TestCase(typeof(Point?), false)]
[TestCase(typeof(StringBuilder), false)]
[TestCase(typeof(DateTime), true)]
[TestCase(typeof(Guid), true)]
[TestCase(typeof(Guid?), true)]
public void IsSimple_WhenCalledForType_ReturnsExpectedResult(Type type, bool expectedResult)
{
var isSimple = TypeAnalyzer.IsSimple(type);
Assert.That(isSimple, Is.EqualTo(expectedResult));
}
}
Finally I changed the in the question mentioned method to:
private bool IsLinkedProperty()
{
return (_propertyInfo != null) && !_propertyInfo.PropertyType.IsSimple();
}
How To Test if Type is Primitive
You can use the property Type.IsPrimitive
, but be carefull because there are some types that we can think that are primitives, but they aren´t, for example Decimal
and String
.
Edit 1: Added sample code
Here is a sample code:
if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String) || ... )
{
// Is Primitive, or Decimal, or String
}
Edit 2: As @SLaks comments, there are other types that maybe you want to treat as primitives, too. I think that you´ll have to add this variations one by one.
Edit 3: IsPrimitive = (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single),
Anther Primitive-Like type to check (t == typeof(DateTime))
C# doubt, finding the datatype
Use meta-data, if you can
That you have to guess what the data types are, is not a good idea.
Two things
1 Where is the data coming from?
If it's a database, are you sure they're strings?
If it is a database, there should be some meta data returned that will tell you what the datatypes of the fields are.
If it's an Xml file, is there a schema defined that will give you the types?
2 If you have to continue to guess.
Be aware that you can have strings that happen to be numbers, but are perfectly valid strings e.g phone numbers, bank acount numbers, that are best expressed as strings.
Also these numbers can have many digits, if you convert them to doubles you may loose some digits to floating point inaccuracies (you should be OK up to 14 or 15 digits)
I'm sure by now - cause I've taken my time typing this - there are lots of answers telling you how to do this (i.e. tryparse int first, then double, then test length for char, if not then it's a string etc), but if I were you, I'd try to NOT do that, and see if there's any way you can get, or pass some meta-data that will tell you what type it IS and not just what type it might be
Related Topics
Mvc: Where to Put Business Logic
How to Install a C# Compiler Without Visual Studio
Is There a Faster Way Than This to Find All the Files in a Directory and All Sub Directories
Determine Operating System in .Net Core
How to Define Properties in Partial Classes, Then Mark Them with Attributes in Another Partial Class
How to Check If a User Belongs to an Ad Group
Get the Sourcecontrol of a Dropdownmenu
What's the Difference Between Utf8/Utf16 and Base64 in Terms of Encoding
How to Copy File - Access to the Path Is Denied
Is Dbcontext the Same as Datacontext
Dynamically Updating Tabcontrol Content at Runtime
How to Use Font Awesome Icons in Project as an Icon of Imagebutton
What Task Is Best Done in a Functional Programming Style
How to Loop Over the Properties of a Class
Switch Between Dotnet Core Sdk Versions
Execute Multiple Queries in Single Oracle Command in C#