Sunday, February 8, 2009

Just Struct It

When will be a good case to use a struct?
Well, let’s look at the following code:

 private IDictionary<IClassKey, string> _someDictionary;

Everything should be working fine here, but what if we need to change our dictionary so it will hold an additional value in addition to the string? It seems like we have a couple of options:
I. We can create a new internal class to hold the data that we need:

 internal class SomeClass
 {
   public string MyString{ get; set; }
   public decimal MyDecimal { get; set; }
 }


and then of course pass it to our dictionary:
 private IDictionary<IClassKey, SomeClass> _someDictionary;

II. Or we can use a struct:

 public struct SomeStruct
 {
   public string MyString{ get; set; }
   public decimal MyDecimal { get; set; }
 


and then of course pass it to our dictionary:

 private IDictionary<IClassKey, SomeStruct> _anotherDictionary;

Now the question that we need to ask is which one should we choose and why.
In this particular case, struct will be a better choice. Creating a new class to hold two variables seems to be too much over-head and too expensive.
Note, that structs are created on the stack and therefore you are dealing directly with the struct object itself and not with its reference.

No comments:

Post a Comment

 
Watch the latest videos on YouTube.com