I would like to use an objects property as the key for a dictionary. Can this be done?
The ultimate goal for this is to use this so can see if the property is locked or not, in various states that an object can be in. These locked value is not persisted, just exist in the business rules for the model.
Ideal code to see if field is locked would look like this;
bool ageLocked = myObject.IsFieldLocked( x => x.Age);
bool nameLocked = myObject.IsFieldLocked(x => x.Name);
IsFieldLocked being an extension method for the type of myObject.
I would like the dictionary to live in myObject and be replaceable with different dictionary variations based on the state of the object, for example, has placed an order or awaiting order would have different dictionary definitions.
Hopefully I would be able to use a factory to create the different dictionary variations;
Factory.CreateAwaitingOrderLockedFields()
Factory.CreateOrderPlacedLockedFields()
Defining the dictionary looking something like this
new Dictionary< ***MissingMagic***, bool>()
{
{ x => x.Age , true},
{ x => x.Name, false}
}
Aim is to avoid the key being a string, strongly typed key by far more desirable.
I'd define the dictionary simply as a
Dictionary<string, bool>
.The extension method then could look something like this:
You will need to implement the IComparable interface in the class you want to use as key in a dictionary:
Since this is not really an option for a member of an object you may was well use
Dictionary<string, bool>
with the field name as the key and a bit of reflection in yourIsFieldLocked()
method to strip out the string from the strongly typed field.You can declare the dictionary with any type as key;
would create a dictionary where form elements are used as key.
Is this What you where asking?
If several different objects are to be used as key you could use
Dictionary<object,bool>
or let all objects inherit from another objectDictionary<masterobject,bool>
.Here is my cut down solution based on advice from herzmeister der welten
With this I can do the following;
I think you should just use inheritance. Create a base class LockedField then create AwaitingOrderLockedField and OrderPlacedLockedField that inherit this class.
You dictionary will be
IDictionary<LockedField, bool>