6

I am working on a C# .NET Application, where I have a Form with lots of controls. I need to perform computations depending on the values of the controls. Therefore, I need to pass the Form values to a function and inside that function, several helper functions will be called depending on the Control element.

Now, I can think of two ways to pass all the Form values:

i) Save everything in a Dictionary and pass the Dictionary to the function or ii) Have a class with attributes that corresponds to each of the Form element.

Which of these two approaches , or any other, is better?

2 Answers2

5

If the attributes that you are tracking are known ahead of time, then a class is the way to go.

If the attributes that you are tracking are not known ahead of time (and which you will just enumerate through later and process all values whatever they are), then a Dictionary<> gives you more flexibility. This is also good if the function is used for elements on different pages that have different types of attributes (allowing you to reuse your function more easily).

You can also consider a hybrid approach:

  1. Have a class that contains some attributes that you know, and has a Dictionary collection that can be used to store some overflow.
  2. Create an enum that stores the names for the elements that you are tracking, and then use the enum as the Key for the Dictionary.
Yaakov Ellis
  • 1,012
4

Use a class. Not only can the class hold the data but it could also store the operations that work on that data. With a dictionary, you'll have to synchronize the code that writes to the dictionary with the code that reads from it. Especially with a large number of fields, this can get messy. Whereas with a class, the compiler verifies the field names for you.

Michael Brown
  • 21,822