Say I had a very simple struct in c#
public struct foo{
public int a{get;set;}
public int b{get;set;}
public int c{get;set;}
public int d{get;set;}
public string hello {get;set;}
}
I take it the above is more ‘efficient’ than using a class?
At what point, if I continued to add string properties, would it be time to convert the struct to a class?
Edit: I had planned to pass this struct around a GDI – centric application.
I had always assumed structs were more performant when dealing with mainly value types.
If you need the enhanced capabilities that a class offers, such as inheritance, then switch. If not, a struct can be a bit “lighter,” but unless you anticipate some performance issues, such as garbage collection inside of a tight loop with a LOT of iterations, the necessity to pass structs around with
refwhenever you want a method to make modifications, etc can create unnecessary work. (Though, in that example, destroying a struct that has reference-type properties also causes GC).The practical upshot being: whether to use a struct or a class is a matter of your use case, not the number of properties that you have.
For a good explanation of the differences between and relative strengths and weakness of classes and structs, see this MSDN article.
For Eric Lippert’s excellent note on garbage collection, structs and classes, see his response to this question.