2

I have a JValue deserialized from JSON and this value represents an enumeration. Consider these two cases:

JValue value = ...

object o1 = value.ToObject(typeof(MyEnum));
object o2 = value.ToObject<MyEnum>();

o1 is of type integer and holds a numeric value of an enum

o2 is of type enum and holds enum value

Why does ToObject method work differently in these two cases?

1 Answer 1

2

Lets say that MyEnum looks like this:

public enum MyEnum
{
    First = 1,
    Second,
    Third
}

and that the JValue is defined like this:

var value = new JValue(MyEnum.First);

When you make call to the following line:

object o1 = value.ToObject(typeof(MyEnum));

you are making a call to the non-generic overload of ToObject method. This method, in the case of enums, resolves the underlying type of the enum, which in this case is int and casts the object to that value. That's why it returns numeric value. (1 in this case).

When you make a call to the generic overload of ToObject method:

object o2 = value.ToObject<MyEnum>();

the result is obtained from the JValue and it is 1 again, but before returning the value, it is casted to the type of the generic type parameter.

To be more clear, here is how the generic overload of ToObject method looks like:

public T ToObject<T>()
{
    return (T)ToObject(typeof(T));
}

It calls the non-generic overload (which we used in the first case), but it casts the result to T before returning it. That's why in the first case we get numeric and in the second case enum value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.