Net-informations.com
SiteMap  | About    

Difference between Classes and Structures

What is the difference between Classes and Structures  C# VB.Net

Technically speaking, structs and classes are almost equivalent, still there are many differences. The major difference like class provides the flexibility of combining data and methods (functions ) and it provides the re-usability called inheritance. Struct should typically be used for grouping data. The technical difference comes down to subtle issues about default visibility of members. Here you can see some of the Difference between Class and Structure.

Class is pass-by-reference and Struct is pass-by-copy, it means that, Class is a reference type and its object is created on the heap memory where as structure is a value type and its object is created on the stack memory. More about .... Difference between a Value Type and a Reference Type

Class can create a subclass that will inherit parent's properties and methods, whereas Structure does not support the inheritance.

Choosing Between Class and Struct C# VB.Net

A class has all members private by default. A struct is a class where members are public by default.

Classes allow to perform cleanup (garbage collector) before object is deallocated because garbage collector works on heap memory. Objects are usually deallocated when instance is no longer referenced by other code. Structures can not be garbage collector so no efficient memory management.

Sizeof empty class is 1 Byte where as Sizeof empty structure is 0 Bytes

Structure vs class in C# VB.Net

Classes are still fit for larger or complex objects and Structs are good for small, isolated model objects. Boxing and unboxing operations are used to convert between a struct type and object. Too much boxing and unboxing can have a negative impact on the heap, the garbage collector, and ultimately the performance of the application.

In general, it's perfectly possible to create structs that look a lot like classes and classes that look a lot like structs.

Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."....... Bjarne Stroustrup









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.