HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Better Alternative For Storing Multiple Booleans?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
alternativebetterformultiplebooleansstoring

Problem

I have a class, which stores an enum to track if my object is modified, newly created, or no change. If the object is modified, I have additional booleans for each field that is modified.

For instance,

public enum status
{
    NoChange,
    Created,
    Modified
}

private bool? name;
private bool? address;
...
private bool? numberOfDonkeysPurchased;


So the idea is that if the status is modified, then the nullable bools will be either true or false, depending on if these fields are changed.

If the status is not modified, then the nullable bools will be null.

The problem with this is that I have a couple of these fields that I want to check (say 10). Is it valid to create a nullable bool for each field that I am checking, knowing that I maybe be storing a lot of nulls? Or is that not a concern?

Is there a better way to store this?

Thanks!

Solution

I would suggest that you use a Dictionary, with the property as the key and the bool as the value. e.g.

Dictionary myProperties = new Dictionary();


Use reflection to get all the properties from your object. Then you dont have any work when properties gets added/removed.

You can initialise your dictionary with reflection like this:

foreach (PropertyInfo propertyInfo in myObject.GetType().GetProperties()) {
    myProperties.Add(propertyInfo.Name, false);
}


Or you can even only add those that are not null.

Code Snippets

Dictionary<string, bool?> myProperties = new Dictionary<string, bool?>();
foreach (PropertyInfo propertyInfo in myObject.GetType().GetProperties()) {
    myProperties.Add(propertyInfo.Name, false);
}

Context

StackExchange Code Review Q#23745, answer score: 4

Revisions (0)

No revisions yet.