Wednesday 11 September 2013

Ref keyword example in C# with structs

In C# if you define a class, then an instance of that class is passed around by reference as it is a reference type.


The above code shows a class called 'Range' which has two int properties, X and Y.

However, if you are familiar with Mircrosoft's suggestions for when to use a struct, you might realise that we should use it here. Microsoft say that a struct should have all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc)
  • It has an instance size under 16 bytes (remember that an int is 4 bytes)
  • It is immutable
  • It will not have to be boxed frequently
Ok so let's define our Range.cs as a struct instead.  All that we need to do is change the keyword 'class' to 'struct'.

Easy peasy. 

Struct defines a value type and so instance of our range object will be passed around by value instead of by references. 

[Note: 
Passing by value: When the object itself is passed around
Passing by reference: Passing a reference to the object in memory]

To illustrate this point imagine that we have 2 move methods, one that takes in a Range and one that takes in a StructRange and moves them diagonally upwards to the right.

Now let's calls these methods:

The output is the following:

          [Range: X=1, Y=1]
          [Range: X=2, Y=2]
          [StructRange: X=1, Y=1]
          [StructRange: X=1, Y=1]

What what? It worked on the range object and moved the coordinates from (1,1) to (2,2) but on the structRange object nothing changed.

When the Move method was called with the structRange, the method was passed copies of the values 1 and 1.  It incremented those values, but the original objects were untouched. To fix this, we need to pass a reference to the struct object to the Move method.  Then the method goes and looks in memory for the ints stored at that memory location and increments them.

Passing by references is shown in the following snippet:

The output is then correct; the move method has been applied:

          [StructRange: X=1, Y=1]
          [StructRange: X=2, Y=2]

No comments:

Post a Comment

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning&#...