0

Possible Duplicate:
When do you use a struct instead of a class?

While working in OOPs, we always battle around structures and classes.

But in real world, we always sticks to classes. I just want to know what is the practical usage of structures in C# and where are they beneficial over the classes.

Or they are just a topic for theory.

0

4 Answers 4

3

Structures are great for representing value types. Things like dates, ranges, numbers; stuff where equality depends on the value of the object rather than the instance of the object. They're good for messages and certain other components in a concurrent program, since the copy semantics make some aspects of that sort of design very clean.

But that's rather in their definition. In practice, they're used more often as a map to some data on disk, or from some other external source since structs can be made to have rules about how they are laid out and packed in memory. So then instead of reading up a byte array and doing the parsing yourself, you can marshal up the structure all at once, letting the runtime do the error-prone stuff.

-1

In C#, structs are value types, while classes are reference types.
So you use a struct whenever a value type is called for, and a class if a reference type is more handy.

That's about all there is to it.

2
  • this is rather begging the question though isn't it
    – jk.
    Dec 6, 2012 at 13:28
  • @jk Yes, but that question has also been answered already! (See list to the right.)
    – Mr Lister
    Dec 6, 2012 at 13:32
-1

My own rule of thumb, it may be wrong:

I'd say a struct is the strong, static typing equivalent of a tuple. Use it when every possible combination of values in the struct is valid and equally reasonable.

On the contrary, classes have a limited set of valid states and have more complex setters and getters, that may need to do validation, too.

1
  • 1
    Dear downvoter, care to explain the downvote? This community is based on sharing knowledge, something you clearly couldn't have possibly had the time to do...
    – K.Steff
    Mar 26, 2019 at 22:05
-1

In C# you are forced to allocate objects on the heap and reference them with a pointer. Structs allow you to put "objects" on the stack. Allocating a value on the stack rather than a pointer affects checks for equality, garbage collection, and the speed of allocation.

C# mixes in a heap vs stack decision. In C++ you can do the opposite of C# if you like and put a class on the stack and struct on the heap. With C++ it comes down to design choices about polymorphism rather than the memory allocation decision that C# forces on you.

1
  • C# doesn't so much force a memory management scheme on you, but abstracts over the (semantic) differences and allows a vast array of implementations.
    – user7043
    Dec 6, 2012 at 14:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.