tags:

views:

81

answers:

2

I'm creating a custom configuration section (inheriting System.Configuration.ConfigurationSection), and I'm wondering if I have to do value validation for a ConfigurationProperty that is a Nullable int. I.e., do I have to do this:

[ConfigurationProperty("NullableInt", IsRequired = true)]
public int? NullableInt
{
    get 
    {
        return String.IsNullOrEmpty(Convert.ToString(this["NullableInt"]))
                    ? (int?) null
                    : Convert.ToInt32(this["NullableInt"]);
    }
    set
    {
        this["NullableInt"] = value.HasValue ? Convert.ToString(value) : "";
    }
}

Or can I just do something like this:

[ConfigurationProperty("NullableInt", IsRequired = true)]
public int? NullableInt
{
    get{ return Convert.ToInt32(this["NullableInt"]); }
    set{ this["NullableInt"] = Convert.ToString(value); }
}

Or is there a better way all-together?

Thanks in advance.

+1  A: 

The first one is the more complete answer.

The second one will work fine in many cases but fails on the edge cases. When writing a section like this you must ensure the simple invariants of the property. Namely that the following will be true for all values of int?

int? v1 = GetSomeNullableIntValue();
obj.NullableInt = v1;
int? v2 = obj.NullableInt;
bool equal = v1 == v2;  // Must be true

Your second example does not make such a guarantee for the null value of int?. Consider how a null int? will be represented in this scenario? Passing in a null int? value to the set will throw and hence can't ever be added to the collection. Likewise, assuming it was stored as null or String.Empty in the config it wouldn't ever come back out again as a null int?

JaredPar
Thanks, both answers here really helped. Marked Miky D's as accepted simply because I understood it better, for some reason. Probably lack of coffee.
AJ
+1  A: 

Well, Convert.ToInt32 will return 0 if the value is null and it will throw an exception if the the expression is not numeric.. so yeah, you want validation! - especially since you want the property to return null for null and not 0 (which is what Convert.ToInt32 would return for null as pointed out earlier)

Also, it may be useful to point out the Int32.Parse() function which is very similar to Convert.ToInt32() but which throws an ArgumentNullException if you attempt to parse null - which is the main difference between the Convert.ToInt32 and the Int32.Parse()

Miky Dinescu
In this case, would you use Int32.Parse() over Convert.ToInt32()? I'm thinking that the String.IsNullOrEmpty() will catch any scenario that Int32.Parse() would fail, would it not?
AJ
Either works.. it really depends on what's your ultimate goal is but don't forget the fact that the the converters will throw exceptions when the expression is not numeric (i.e. 'a123bcd') So maybe a try catch would be in order.. and the use of Int32.Parse() to simplify things..
Miky Dinescu