This question already has answers here:
Closed 8 years ago.
Possible Duplicate:
Which is best for data store Struct/Classes?
Consider the example where I have an Employee object with attributes like age, name, gender, title, salary. I now have a list i want to populate with a bunch of Employees (each Employee instance is unique).
In terms of just speed and memory footprint, is it more preferable to create the employee as a Struct or a Class?
Any additional caveats regarding Struct vs Class in the above scenario are welcome
Structs are to be used only for relatively small structures that should have value-like behaviour.
- Class and struct differences
- Choosing Between Classes and Structures
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.
Your type breaks the first two guidelines, and probably also the third. So you should definitely use a class here.
It isn't as simple as that - you need to describe the behaviour. For example, a struct
will copy itself as soon as you like, so in some ways they can consume more memory. However, an array of structs as a raw data dump can avoid a (very small) object header (and an extra dereference), so can have efficiencies.
A bigger issue, though, is in how you conceptualise them; an Employee is not a value; if I assign:
var emp = GetEmployee();
var tmp = emp;
does that mean I should now have 2 employees? It proabably doesn't. Now what if I change:
tmp.Name = "Fred";
whether this impacts emp
depends on whether it is struct or class. I wager it should be class here. I also propose that a struct should almost always be immutable to avoid this type of data-loss scenario. There is case for mutable structs, but it is so often used incorrectly that I don't want to accidentally encourage you to do that.
Other issues arise with encapsulation with structs; consider that an employee has a manager; is this possible?
[struct|class] Manager {
private Manager boss;
}
this only works for a class. Again; structs are not well suited to this type of usage. Nor polymorphism, abstraction, etc.
That depends, probably a class would be fine in this case. Hope below points help you to decide.
Use of structure in following condition is desirable.
When you have small data structure
Data Structure does not require to extent the functionality.
When you want to perform faster operation on data structure. (As structure are stored on stack, operation performed on it are faster.)
Use of class in following condition is desirable.
When you have complex data structure
Data Structure requires to extend functionality.
When you want to optimize memory usage. (As class is stored on heap, they are about to be garbage collected when no reference pointing to an object.)
Look at here for more details.