What are the differences between a struct and a class?
Use a class if:
- Its identity is important. Structures get copied implicitly when being passed by value into a method.
- It will have a large memory footprint.
- Its fields need initializers.
- You need to inherit from a base class.
- You need polymorphic behavior;
Use a structure if:
- It will act like a primitive type (int, long, byte, etc.).
- It must have a small memory footprint.
- You are calling a P/Invoke method that requires a structure to be passed in by value.
- You need to reduce the impact of garbage collection on application performance.
- Its fields need to be initialized only to their default values. This value would be zero for numeric types, false for Boolean types, and null for reference types.
- Note that in C# 6.0 structs can have a default constructor that can be used to initialize the struct’s fields to nondefault values.
- You do not need to inherit from a base class (other than ValueType, from which all structs inherit).
- You do not need polymorphic behavior.
Comments
Post a Comment