public class Customer
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public struct Customer
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Customer { public int CustomerId { get; set; } public string FirstName
Share
Your second snippet is a mutable struct. That’s a really bad idea, IMO – they behave oddly in various different situations, as values can be copied when you may not expect them to be.
You could create immutable structs of course, and there are times when that’s appropriate – but personally I find the reference type behaviour more natural usually. With structs, you also need to worry about the fact that whatever constructors you put in place, it’s always possible to set a variable to the default value – so the fields will be zero for numeric types, null for reference types etc. It’s annoying to have to deal with the possibility of an invalid object everywhere, whereas with classes you can add appropriate validation to the constructor (or factory methods) to make sure that the only thing you need to worry about is a null reference.
The efficiency argument ends up tricky, as there are pros and cons on both sides, depending on exactly what you do with the objects.
To cut a long answer short (too late?) – I would use classes by default; save value types for things which are natural individual values (“an instant in time”, or “an integer” for example).