C# - Purposes of struct and class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?...

7th Mar 2017, 10:25 PM
Geoffrey L
Geoffrey L - avatar
5 Answers
+ 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.
7th Mar 2017, 11:52 PM
Wen Qin
Wen Qin - avatar
+ 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.
7th Mar 2017, 10:55 PM
AtoMX
AtoMX - avatar
+ 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?
7th Mar 2017, 10:59 PM
Geoffrey L
Geoffrey L - avatar
+ 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
7th Mar 2017, 11:26 PM
AtoMX
AtoMX - avatar
+ 2
Oh ok! Thanx for all these details I didn't imagine that, that's interesting!
7th Mar 2017, 11:30 PM
Geoffrey L
Geoffrey L - avatar