What is a Class and structure’s?
Structures are value types and classes are reference types..
When to use Structures and When to use classes?
You will use structures when: –
Point 1:- If you want to represent a custom value type. This custom value type is derived from primitive data types (int, double). Some of the example’s of custom types are co-ordinates (which have X, Y), complex numbers (which have real and imaginary components). You can also term these things as value objects or technical objects. Technical objects do not represent real world objects like customer, supplier, invoice etc.
Point 2:- If you want to have low memory foot print. For instance let’s say you want to plot a graph. To plot a graph you need to have 100’s of objects created so that you can represent co-ordinates. Now if you create a class and generate those 100’s of objects you end up putting lot of load on your garbage collector. If you create a “struct” , it’s a value type. So they get created and destroyed immediately. Thus putting less load on memory.
For all other scenarios use a class.
What are similarities between Class and structure?
Following are the similarities between classes and structures:-
- Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
- Structures and classes can implement interface.
- Both of them can have constructors with and without parameter.
- Both can have delegates and events.
What is the difference between Class and structure’s?
Following are the key differences between them:-
- Structures are value types and classes are reference types. So structures use stack and classes use heap.
- Structures members cannot be declared as protected, but class members can be. You cannot do inheritance in structures.
- Structures do not require constructors while classes require.
- Objects created from classes are terminated using Garbage collector. Structures are not destroyed using GC.
Click and see here for more basics training in .NET