I'm working with a sealed
Singleton
Settings
class, where I've found following definition of a property:
public Boolean aRandomProperty
{
get
{
return (Boolean)this["aRandomProperty"];
}
set
{
this["aRandomProperty"] = value;
}
}
While having a look at the source code, I've seen that this property is used as:
SomeOtherVariable = Settings.Instance.aRandomProperty;
Settings.Instance.aRandomProperty = true;
I believe that a simple definition of the property, like the following, would work too:
public Boolean aRandomProperty;
Can anybody explain me what more can be done with that difficult getter/setter definition (I also completely don't understand the this["aRandomProperty"]
part)?
For your information: the Settings
class is derived from System.Configuration.ApplicationSettingsBase
.
Nowhere in the code, there is this[
(even not with a bunch of spaces), so I believe there's no indexer defined.
Using get
and set
, you define a property whereas with your proposed code (public Boolean aRandomProperty;
) a simple field is declared. As @VinayC also explains, properties look like fields from the outside, but are defined as code. This way, a property hides the details of the class and enable you to
Especially the latter is important when we look at your specific example:
public Boolean aRandomProperty
{
get
{
return (Boolean)this["aRandomProperty"];
}
set
{
this["aRandomProperty"] = value;
}
}
This property uses the indexer of the base class to store the data. In your case, the base class ApplicationSettingsBase
is used to access the configuration of the application. This class offers a so called indexer, a specific kind of property that is defined like this:
public object this[string key]
{
get
{
// Retrieve data using the key
}
set
{
// Store data using the key
}
}
This kind of property allows your class (or in this case the base class) to be used like:
var myInstance = new MyClassWithAnIndexer();
myInstance["test"] = 123;
var value = myInstance["test"];
This is often used to store arbitrary data in your class without knowing their name/key beforehand. Configuration settings are a good example for this as they usually are put together from key-value-pairs where key can be anything.
Wrapping up, the aRandomProperty
in your sample is a property that uses the indexer of the base class to store and retrieve the value. Possible reasons for this are
The documentation provides details on properties and indexers.