Reputation: 8682
public string AgentVersion
{
get { return m_version; }
} // property: Enabled
private string m_version = null;
The below declaration coding i did in Constructor
string keySpoPath = SpoRegistry.SpoAgentRoot;
RegistryKey regkey = Registry.LocalMachine.OpenSubKey(keySpoPath);
m_version = (string)regkey.GetValue(SpoRegistry.regValue_CurrentVersion);
here are my doubts
Do I need private string m_version = null;
in property declaration in this context? If I remove that one, are there any probs?
If AgentVersion
is null
or not getting any value or any strings other than numeric values I want to assign AgentVersion to value '0.0.0.0' otherwise i will
display the numeric value which is coming. Is this code below sufficient here
string.IsNullOrEmpty(AgentVersion) ? "0.0.0.0" : AgentVersion;
If then where and how can I implement in 'Property'
Upvotes: 0
Views: 257
Reputation: 574
1) You don't need to instantiate m_version
as null in this context. You usually only need to do this when declaring a local variable, to avoid the 'Use of unassigned local variable [name]' compile error. So private string m_version;
will suffice.
2) For checking null and empty values, what you have with String.IsNullOrEmpty()
is fine. If you want to go check your property returns strings in the correct format, you can use Regex.IsMatch()
to ensure the property only ever returns strings in version number-format.
[DefaultValue("0.0.0.0")]
public string AgentVersion
{
get
{
return System.Text.RegularExpressions.Regex.IsMatch(m_version ?? String.Empty, @"\A\d+[.]\d+[.]\d+[.]\d+\z")
? m_version
: "0.0.0.0";
}
}
private string m_version;
My regular expressions are a bit rusty, so someone can probably improve on what I have here, but it's the general gist of what you need.
Upvotes: 0
Reputation: 19238
you can use this code.
public string AgentVersion
{
get
{
if(string.isNullOrEmpty(m_version))
{
string keySpoPath = SpoRegistry.SpoAgentRoot;
RegistryKey regkey = Registry.LocalMachine.OpenSubKey(keySpoPath);
m_version = (string)regkey.GetValue(SpoRegistry.regValue_CurrentVersion);
}
m_version = string.isNullOrEmpty(m_version) ? m_version : "0.0.0.0";
return m_version;
}
}
string m_version;
Upvotes: 1
Reputation: 1039428
m_version
is always assigned in the constructor you don't need setting it to null
.get { return string.IsNullOrEmpty(m_version) ? "0.0.0.0" : m_version; }
Upvotes: 2
Reputation: 68737
You can use Resharper, it will show you where you have redundant declarations. In this case it is redundant.
If String.Empty
is a valid value you can implement it using
public string AgentVersion
{
get { return m_version ?? "0.0.0.0"; }
}
otherwise you are correct use String.IsNullOrEmpty
public string AgentVersion
{
get { return String.IsNullOrEmpty(m_version) ? "0.0.0.0":m_version; }
}
Upvotes: 1