Is there a function to check if an object is a builtin data type?

前端 未结 3 2000
日久生厌
日久生厌 2020-12-10 18:58

I would like to see if an object is a builtin data type in C#

I don\'t want to check against all of them if possible.
That is, I don\'t want to do this:

3条回答
  •  自闭症患者
    2020-12-10 19:49

    Not directly but you can do the following simplified check

    public bool IsBulitin(object o) {
      var type = o.GetType();
      return (type.IsPrimitive && type != typeof(IntPtr) && type != typeof(UIntPtr))
            || type == typeof(string) 
            || type == typeof(object) 
            || type == typeof(Decimal);
    }
    

    The IsPrimitive check will catch everything but string, object and decimal.

    EDIT

    While this method works, I would prefer Jon's solution. The reason is simple, check the number of edits I had to make to my solution because of the types I forgot were or were not primitives. Easier to just list them all out explicitly in a set.

提交回复
热议问题