Alex Rivera | Logout

C#, struct vs class, faster?

Asked 2011-09-20T11:57:29.487
24

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

Edit
Report

1 Answer

15

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.

answered 2011-09-20T12:02:35.597

Your Answer