+ 1
C# - Purposes of struct and class?
I'm learning C# and I have to say that it's moving a little bit my php knowledge by adding Structure to compete with Class. I have mostly understand the idea and difference of them but I don't imagine yet in what kind condition that will be better to use Class and in what condition use Structure. Is it purely an organisation functionality? a memory reason?...
5 Antworten
+ 5
Structures will be better than classes when you want to store some basic functions and variable and constantly reuse, and change them throughout the code.
Classes will be better for doing more complex stuff, longer codes. Also, making it inherit another class, that is one important thing of why I use classes.
+ 2
Structs may seem similar to classes, but classes are reference types and structs are value types.
By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.
+ 2
Thanx for your answer atoMX! You confirm what I understood but I'm wondering advantages of both, in what condition we will prefer to use a class, in what condition structure are more interesting that class?
+ 2
In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
- class can be used to store data retrieved from db (orm mapper), file (json, xml), services
- struct can be used to store settings, coordinates (latitude, longitude), point
+ 2
Oh ok! Thanx for all these details I didn't imagine that, that's interesting!