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.
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()