Programmer Puzzle - Class and struct |
Page 1 of 2 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.
BackgroundC# 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... PuzzleYou 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 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 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.
<ASIN:B09FTLPTP9> |