Programmer Puzzle - Class and struct
Article Index
Programmer Puzzle - Class and struct

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.





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...



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)

This all works. If you try:

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

you will find that p1 is constructed correctly and zeroed correctly by 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 };

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.


Deep C# - Custom Attributes In C#

The role of custom attributes in C# can be confusing. They are easy to use when supplied, but how do you go about creating custom attributes? And when are they useful? 

Deep C#: Strong Typing

C# is a strongly typed langauge but what does this mean and why is it good. Find out in this extract from my new book Deep C#.

Deep C# - Value And Reference

Value and reference are a fundamental division in the way C# treats data. It is important that you understand the differences and, most importantly, when to use a struct and when to use a class. These [ ... ]

Deep C# - Structs & Classes

Classes can do the same job as C# structs - so why both? Find out in this extract from my new book, Deep C#:Dive Into Modern C#.

Not So Complex Numbers in C#

Did you know that .NET supports complex numbers? The Complex struct is easy to use and just needs a little extra publicity so that we all remember it's there!

Deep C# - Inheritance

Inheritance - is it where it all goes wrong? Find out in this extract from my new book, Deep C#: Dive Into Modern C#.

Other Articles