When Should I Use a Struct Rather Than a Class in C#

When should I use a struct instead of a class?

MSDN has the answer:
Choosing Between Classes and Structures.

Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria.

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.

Should I use a structure instead of a class to hold string only data in C#?

I can't see any value in making the customer a struct. The string fields will all be reference types, so you might as well make the whole thing a reference type (ie. class).

I'd be inclined to use one of the built-in collection types rather than create my on type for Customers. Something like:

List<Customer> Customers = new List<Customer>();

When should you use a class vs a struct in C++?

The differences between a class and a struct in C++ is:

  • struct members and base classes/structs are public by default.
  • class members and base classes/struts are private by default.

Both classes and structs can have a mixture of public, protected and private members, can use inheritance and can have member functions.

I would recommend you:

  • use struct for plain-old-data structures without any class-like features;
  • use class when you make use of features such as private or protected members, non-default constructors and operators, etc.

Structs versus classes

Is it faster to create these objects as class or as struct?

You are the only person who can determine the answer to that question. Try it both ways, measure a meaningful, user-focused, relevant performance metric, and then you'll know whether the change has a meaningful effect on real users in relevant scenarios.

Structs consume less heap memory (because they are smaller and more easily compacted, not because they are "on the stack"). But they take longer to copy than a reference copy. I don't know what your performance metrics are for memory usage or speed; there's a tradeoff here and you're the person who knows what it is.

Is it better to create these objects as class or as struct?

Maybe class, maybe struct. As a rule of thumb:
If the object is :

1. Small

2. Logically an immutable value

3. There's a lot of them

Then I'd consider making it a struct. Otherwise I'd stick with a reference type.

If you need to mutate some field of a struct it is usually better to build a constructor that returns an entire new struct with the field set correctly. That's perhaps slightly slower (measure it!) but logically much easier to reason about.

Are objects on the heap and the stack processed equally by the garbage collector?

No, they are not the same because objects on the stack are the roots of the collection. The garbage collector does not need to ever ask "is this thing on the stack alive?" because the answer to that question is always "Yes, it's on the stack". (Now, you can't rely on that to keep an object alive because the stack is an implementation detail. The jitter is allowed to introduce optimizations that, say, enregister what would normally be a stack value, and then it's never on the stack so the GC doesn't know that it is still alive. An enregistered object can have its descendents collected aggressively, as soon as the register holding onto it is not going to be read again.)

But the garbage collector does have to treat objects on the stack as alive, the same way that it treats any object known to be alive as alive. The object on the stack can refer to heap-allocated objects that need to be kept alive, so the GC has to treat stack objects like living heap-allocated objects for the purposes of determining the live set. But obviously they are not treated as "live objects" for the purposes of compacting the heap, because they're not on the heap in the first place.

Is that clear?

What's the difference between struct and class in .NET?

In .NET, there are two categories of types, reference types and value types.

Structs are value types and classes are reference types.

The general difference is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.

A variable containing a value type contains the entire value type value. For a struct, that means that the variable contains the entire struct, with all its fields.

A variable containing a reference type contains a pointer, or a reference to somewhere else in memory where the actual value resides.

This has one benefit, to begin with:

  • value types always contains a value
  • reference types can contain a null-reference, meaning that they don't refer to anything at all at the moment

Internally, reference types are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:

  • copying the contents of a value type variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other
  • copying the contents of a reference type variable into another variable, copies the reference, which means you now have two references to the same somewhere else storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places

When you declare variables or fields, here's how the two types differ:

  • variable: value type lives on the stack, reference type lives on the stack as a pointer to somewhere in heap memory where the actual memory lives (though note Eric Lipperts article series: The Stack Is An Implementation Detail.)
  • class/struct-field: value type lives completely inside the type, reference type lives inside the type as a pointer to somewhere in heap memory where the actual memory lives.

In C#, when should I use a struct and when should I use a class?

You should use a class unless you have a very specific reason to use a struct. I realize it's a little bit trite, but it's true (trite and true! hah! right?)

Struct v/s Class in C# - Please explain the behavior

Classes are reference types, structs are value types.

When a value type is passed to a method as a parameter, a copy of it will be passed through. That means that you add two completely separate copies of the Person struct, one for each pass in the loop.

When a reference type is passed to a method as a parameter, the reference will be passed through. That mean that you add two copies of the reference to the same memory location (to the same Person object) - when making changes to this one object, you see it reflected in both references since they both reference the same object.



Related Topics



Leave a reply



Submit