Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get ConfigurationSection property as a System.Type

i want to define a custom configuration section and have a property not yield a string but a system.type (or null if the user types in a load of rubbish)

e.g.:

<myCustomConfig myAnnoyingType="System.String" />

in the C# (in the current real world)

[ConfigurationProperty("myAnnoyingType")]
public string MyAnnoyingType
{
   get { return (string)this["myAnnoyingType"]; }
}

// else where in the app
var stringType = thatConfig.MyAnnoyingType
var actualType = Type.GetType(stringType);
// wow that was boring.

in the C# (in an ideal world)

[ConfigurationProperty("myAnnoyingType")]
public Type MyAnnoyingType
{
    get { return (Type)this["myAnnoyingType"]; }
}

What I want is NOT to have to keep the item as a string in the C# and then convert that into a Type in the application; i'd like this to be done automatically as part of the responsibility of the ConfigurationManager.

Is this possible? I'm OK to use a TypeConverter if I have to be, it just seems so weak to keep it as a string and then do the type lookup in the application. It's not hard to do, just seems pointless when I know i'm looking for a type, what is the value of having to explicitly do it.

like image 208
peteisace Avatar asked Jul 02 '15 23:07

peteisace


1 Answers

Try using a TypeConverterAttribute that will do the conversion for you. This worked for me.

    [ConfigurationProperty("type")]
    [TypeConverter(typeof(TypeNameConverter))]
    public Type Type
    {
        get
        {
            return (System.Type)this["type"];
        }
        set
        {
            this["type"] = value;
        }
    }
like image 160
davidlbaileysr Avatar answered Sep 19 '22 19:09

davidlbaileysr