What's the point of having AppSettingsReader ask for a value type and return a non-specific type object?

I don't understand why the framework exposes AppSettingsReader.GetValue whose signature is:

public object GetValue(string key, Type type);

      

asks for the type of the setpoint and returns non casted object

?! What's the point of asking for a type and not exposing the generic value of the type ?!

I wonder why they didn't finish the job.

If we're already talking about shutting down, perhaps the following should be what we would like:

public T GetValue<T>(string key, T defaultValue = default(T)) where T : class
{
    object value = _appSettingsReader.GetValue(key, typeof(T));
    T castedValue;
    try
    {
        castedValue = (T) Convert.ChangeType(value, typeof(T));
    }
    catch (Exception)
    {
        castedValue = defaultValue;
    }

    return castedValue;
}

      

+3


source to share


1 answer


What's the point of asking for a type and not exposing the generic value of the type ?!

Well, I guess they wrote this code before the era of generics. This method has been there since .NET 1.1, so definitely pre-generic.



The point in the type query is that behind this method it will convert the value to the desired type. He is simply not exposed to the outside world. He needs to know how to read XML and convert it to a specific type.

Of course, they could (and probably should) rewrite this code to use generics. It will benefit all of us.

+3


source







All Articles