Class and struct
Article Index
Class and struct
Solution

This C# puzzle shouldn't be difficult as long as you are secure in your understanding of class and structs. See if you can spot the danger as soon as you read it.

 

Banner

 

Background

C# has two ways to define new object types - structs and classes. The struct is often referred to as a lightweight class because it is implemented on the stack, doesn't have to be garbage collected and doesn't support inheritance. The advice is often given that you should use a struct when performance is important.

This isn't quite the full story...

Banner

Puzzle

You start off with a very simple design for 2D plotting program and decide to use a class to implement a simple point object:

public class point
{
public  int x;
public  int y;
}

Now you decide that you need a method that zeros an arbitrary point object:

public void ZeroPoint(point p)
{       
p.x=0;
p.y=0;
}

This all works. If you try:

point p1 = new point() { x = 10, y = 20 };
ZeroPoint(p1);

you will find that p1 is constructed correctly and zeroed correctly but ZeroPoint - that is after ZeroPoint p1.x and p1.y are zero.

Now a little later on the programmer is convinced by one of those discussions you sometimes have that a point object should be a struct because it's more efficient.

The change is just one keyword:

public struct point
{
public  int x;
public  int y;
}

That is, class becomes struct. No other changes are made to the program but after the change ZeroPoint no longer works.

When you check the code:

point p1 = new point() { x = 10, y = 20 };
ZeroPoint(p1);

the value of p1.x is now 10 and p1.y is now 20.

All that has happened is a change from class to struct. How can this effect the way a method works?

Turn to the next page when you are ready to find out.

<ASIN:1449380344>

<ASIN:1430225378>
<ASIN:0470447613>

<ASIN:1933988924>