You shouldn't trust the value from the registry since a user can edit it outside your application. You need to handle the following cases:
- registry key doesn't exist
- registry key exists, but name/value doesn't exist (
null)
- you expect a
string, value is not string type (e.g. it is an int or byte[])
- value is a
string but not parsable to decimal ("", "abc")
If the key doesn't exist, RegistryKey.OpenSubKey(name) returns null. You might want to handle that and create the key. If the key exists, but not the name/value pair, then RegistryKey.GetValue(name) returns null. You can handle that by passing a default value to the overload RegistryKey.GetValue(name, defaultValue) or by using ??.
Now, if the name/value pair exists but has an invalid value ("", "abc"), you'll get an exception from Parse(). The Parse() methods (in int, decimal, DateTime, etc) have been pretty much been deprecated by TryParse(). They return false instead of throwing FormatException.
// passing the default value to GetValue()
object regValue = APRegistry.GetValue("apTime", "0");
// ...same as...
object regValue = APRegistry.GetValue("apTime") ?? "0";
decimal value;
// regValue will never be null here, so safe to use ToString()
if(decimal.TryParse(regValue.ToString(), out value))
{
this.apTime.Value = value;
}
else
{
// Name/pair does not exist, is empty,
// or has invalid value (can't parse as decimal).
// Handle this case, possibly setting a default value like this:
this.apTime.Value = 0;
}