Q: What do structs buy you?
Q: How are structs different from classes?
Q: How do structs impair code readability and maintainability? Even though structs and classes work differently, they look the same. This makes the code hard to follow. C# violates a principle of programming language design, known as the principle of uniformity.
Q: What is the principle of uniformity and why should I care? If a programming language violates this principle then it increases complexity, and code written in that language becomes harder to understand and maintain. Because of C#'s violation of the principle of uniformity, the programmer has the extra burden of tracking whether something is a struct or a class.
Q: Isn't that a problem in C++ too?
Q: Why should I track whether something is a struct or a class? In C++, this is usually visible in the declaration of the variable (Foo f for a value type, Foo *pF for a pointer) and in its use (f.x for a value type, f->x for a reference type). In C#, both use the same syntax for declaration and use, and there isn't even any suggested name standard to mark the difference. In just about every case, it's important to know if you are dealing with value types or reference types — reference types has the concept of identity and equality, while value types only has equality. Allocating an array of value types gives you a number of objects with default values while an array of reference types gives you a array of null references. Adding a struct type to a list means it's silently boxed and removing it unboxes it at a significantly higher cost than if a reference types were added removed. Etc, etc. [credit: Mats Olsson]
Q: What can we conclude from all this?
|