web analytics

Choosing Between Classes and Structures in .NET

Options

codeling 1602 - 6666
@2016-01-31 23:44:22

In .NET languages, such as C#, classes are reference types and structures are value types. Reference types are allocated on the heap, and memory management is handled by the garbage collector. Value types are allocated on the stack or inline and are deallocated when they go out of scope. In general, value types are cheaper to allocate and deallocate. However, if they are used in scenarios that require a significant amount of boxing and unboxing, they perform poorly as compared to reference types.

Do not define a structure unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (integer, double, and so on).

  • It has an instance size smaller than 16 bytes.

  • It is immutable.

  • It will not have to be boxed frequently.

If one or more of these conditions are not met, create a reference type instead of a structure. Failure to adhere to this guideline can negatively impact performance.

@2016-01-31 23:47:07

Besides the performance impact, it is said that structures should not be used because they violate the Principle of Uniformity which says that users/programmers expect that things that look similar should do similar things, and conversely that things that look different should do different things, consider the following example:

    Point a = new Point(10, 10);
Point b = a;
a.x = 100;
Console.WriteLine(b.x);

What will this code snippet print? The answer depends on whether Point is a class or a struct. If Point is a class then the answer is 100. If Point is a struct then the answer is 10.

Even though structs and classes work differently, they look the same. This voilation of principle of uniformity makes the code hard to follow.

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com