peteisace
peteisace

Reputation: 2772

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.

Upvotes: 7

Views: 1153

Answers (2)

davidlbaileysr
davidlbaileysr

Reputation: 684

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;
        }
    }

Upvotes: 7

kyrylomyr
kyrylomyr

Reputation: 12632

First, its better to define a type in your settings using the fully qualified name. This way you get less problems with resolving the Type from the string.

Second, you need to find the Type by it's string name as was already answered in Convert String to Type in C# because it's not possible just cast string to Type.

In your case it would be:

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

Upvotes: 3

Related Questions