C# The little things that bite (I)

on

Even as an experienced developer, my code can sometimes bite me (hard). Being “experienced” doesn’t spare you from newbie mistakes. You’ll just be laughing at yourself for doing it soon after.

“The struct that bites”

Consider this…

var dict = new Dictionary<int, StructA>();
dict.Add(1, new StructA());
dict[1].SomeProp = SomeNewValue;

The bite comes when I expect what is in the dictionary to change, except it doesn’t. Oops! Newbie mistake there. Now if “StructA” is a “Class” instead, it works fine.

Class is a reference type, whereas struct is a value type. When we assign a struct to a variable, a copy is made. In the example above, dict[1] makes a copy as a temporary variable, not a reference to it. So the statement won’t do a thing to what is in the dictionary.

It can give an impression that structs are immutable which is incorrect. (http://stackoverflow.com/questions/3751911/why-are-c-sharp-structs-immutable)

Simple stuff but easy bugs…

Reference:
https://msdn.microsoft.com/en-us/library/ms173109.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s