Reputation: 946
I have a dictionary set up like so: Dictionary <string, ItemProperties>
the ItemProperties object looks like this (the base class is abstract):
public class StringProperty : ItemProperty
{
public string RawProp { get; set; }
public string RenderedProp { get; set; }
}
Is there a way to get the RenderedProp value like so (assuming the dictionary variable is called Properties):
string value = Properties[keyname];
versus
string value = Properties[keyname].RenderedProp;
Upvotes: 1
Views: 1435
Reputation: 180787
You can create your own PropertyDictionary
with a custom Indexer method.
public class PropertyDictionary
{
Dictionary <string, StringProperty> dictionary;
public PropertyDictionary()
{
dictionary = new Dictionary <string, StringProperty>();
}
// Indexer; returns RenderedProp instead of Value
public string this[string key]
{
get { return dictionary[key].RenderedProp; }
set { dictionary[key].RenderedProp = value; }
}
}
Upvotes: 5
Reputation: 6060
You could implement an extension method for your Dictionary<>:
public static int GetRP(this Dictionary <string, ItemProperties> dict, string key)
{
return dict[key].RenderedProp;
}
You'd have to call it directly though, without having the indexer notation. Overall code is similarly short if you use a short name.
Upvotes: 1
Reputation: 726479
There is a solution, but I would strongly recommend against it: define an implicit conversion operator from StringProperty
to string
, and return RenderedProp
to the caller:
public class StringProperty : ItemProperty
{
public string RawProp { get; set; }
public string RenderedProp { get; set; }
public static implicit operator string(StringProperty p)
{
return p.RenderedProp;
}
}
The Dictionary
needs to use StringProperty
, not ItemProperty
as the value type in order for the operator to apply. The same is true about your Properties[keyname].RenderedProp
code as well.
Upvotes: 2
Reputation: 1499780
No. If you want to store the RenderedProp
value in the dictionary, just make it a Dictionary<string, string>
and add it appropriately. If you do actually need the full ItemProperties
in the dictionary, but frequently want to get at the RenderedProp
, you could always create a method to do that (wherever the dictionary lives).
Note that if RenderedProp
is only specified in StringProperty
(not in other subclasses of ItemProperties
) then you need to consider what would happen for non-StringProperty values in the dictionary.
Upvotes: 3