Reputation: 7
What does
public object this[string name]
do
class ObjectWithProperties
{
Dictionary<string, object> properties = new Dictionary<string, object>();
public object this[string name]
{
get
{
if (properties.ContainsKey(name))
{
return properties[name];
}
return null;
}
set
{
properties[name] = value;
}
}
}
Upvotes: 0
Views: 100
Reputation: 141
You will be able to reference the values in your dictionary directly from your object using indexes (ie, no property name)
In your case it would be
var foo = new ObjectWithProperties();
foo["bar"] = 1;
foo["kwyjibo"] = "Hello world!"
// And you can retrieve them in the same manner...
var x = foo["bar"]; // returns 1
MSDN guide: http://msdn.microsoft.com/en-gb/library/2549tw02.aspx
Basic tutorial: http://www.tutorialspoint.com/csharp/csharp_indexers.htm
Edit to answer question in comment:
This is equivalent to doing something like the following:
class ObjectWithProperties
{
public Dictionary<string, object> Properties { get; set; }
public ObjectWithProperties()
{
Properties = new Dictionary<string, object>();
}
}
// instantiate in your other class / app / whatever
var objWithProperties = new ObjectWithProperties();
// set
objWithProperties.Properties["foo"] = "bar";
// get
var myFooObj = objWithProperties.Properties["foo"]; // myFooObj = "bar"
Upvotes: 6