Home > Software design >  c# Is there a way to determine if an object value is a base type like ints and strings or like class
c# Is there a way to determine if an object value is a base type like ints and strings or like class

Time:05-24

I want to make a serializer and to do this I have to check if the current object's type can hold multiple values. (What I mean by base type are Strings and Ints)

I know there are a lot of great serializers out on the internet but I am doing this as a challenge and most of them don't have the features I want

I guess ints and strings are also classes but what I want is like this:

bool CheckIfBaseType(object value)  { return //check }

I don't think there is a proper way to do this instead of saving each base type in an array

Edit:

I think I can use reflection to check if there are any public variables but is there a better way to do this?

Edit 2:

Ok, I am going to try to explain it a bit more, so what I really want is a function that can detect if a value can hold another value so I can check the child value

Algorithmic explanation:

    if(objectCanHoldValues(value))
    {
        //switch the target object to the child object and check if 
        it can hold a value (this part is done)
    }

please do not dislike when I say your solution doesn't work. I am really new to the Stack overflow if I make a mistake I am sorry

CodePudding user response:

This is what you are looking for?

public static class TypeExtensions
{

    private static HashSet<Type> otherScalarTypes = new HashSet<Type>
    {
        typeof(string), typeof(Guid), typeof(DateTime),
        typeof(DateTimeOffset)
    };

    public static bool IsScalar(this Type type)
    {
        return type.IsPrimitive || otherScalarTypes.Contains(type);
    }
}

Note that Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single are primitive types.

Then you can check if it is a "base type":

if (obj.GetType().IsScalar()) 
{

}

CodePudding user response:

Use .Net Reflection to check IsPrimitive, IsArray, or for other types

enter image description here

  • Related