Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Struct usage tips?

I like using structs a lot.

So after reading this article, are there any other concerns I should have against using them all the time?

See Also:

  • When should I use a struct instead of a class?
  • When to use struct in C#?
like image 499
matt_dev Avatar asked Mar 12 '09 21:03

matt_dev


3 Answers

You should make the following considerations about structs:

  • structs should be immutable (mutable structs are not intuitive and unpredictable)
  • structs always have a default (public parameterless) constructor that cannot be changed
  • struct size should not exceed 16 bytes
  • the Equals and GetHashCode methods should be overriden for better performance
  • implementing the IEquatable<T> interface is recommended
  • redefining and == and the != operators is also recommended
like image 52
Michael Damatov Avatar answered Oct 05 '22 20:10

Michael Damatov


I almost never define custom structs. There just aren't that many natural value types around, IMO.

In particular, I would think very, very carefully before defining a mutable struct, especially if it mutates via an interface implementation. Mutable structs behave in ways which people don't expect at all, leading to code which is hard to understand.

I think it's worth reading "Choosing Between Classes and Structures" from "Design Guidelines For Developing Class Libraries".

In particular:

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.

Do you really develop types with all of those characteristics frequently?

like image 37
Jon Skeet Avatar answered Oct 05 '22 21:10

Jon Skeet


They don't fit into an Object Oriented programming paradigm like classes do. They are good for small data structures, but I use classes for anything beyond that.

like image 31
Ed S. Avatar answered Oct 05 '22 20:10

Ed S.