Michael Michael - 1 month ago 26
ASP.NET (C#) Question

Understanding ValueProviderResult.ConvertTo(Type) Method

I don't quite understand the point of this method.

It converts a ValueProviderResult to an Object.. but the Method takes a parameter of Type that its supposed to convert to. So what is the point? or why does it require Type argument if it will always just return a type of object?

Here is an working example:
You can see that after I convert it, I still have to cast it to its proper type.

RequestTypeEnum requestType = (RequestTypeEnum)(object)bindingContext.ValueProvider.GetValue(requestTypePropertyName).ConvertTo(typeof(RequestTypeEnum));

Answer

The underlying object will be an instance of the Type entered.

The point of the method

ValueProviderResult.ConvertTo Method (Type)

Converts the value that is encapsulated by this result to the specified type.

You can always create a generic extension method if you want to work with concrete types

///<summary>
/// Converts the value that is encapsulated by this result to the specified type.
///</summary>
public static class ValueProviderResultExtension {
    public static T ConvertTo<T>(this ValueProviderResult valueProvider) {
        return (T) valueProvider.ConvertTo(typeof(T));
    }
}

Which is then used like

RequestTypeEnum requestType = bindingContext.ValueProvider.GetValue(requestTypePropertyName).ConvertTo<RequestTypeEnum>();