Sunday, March 26, 2017

Differences between Class and Struct Asp Net


Today we will discuss the difference between class and struct in Asp.Net. As we already know that .Net is object oriented based so it has inside all concepts of OOP with their context.
If you have a little bit idea what is Reference Type and What is Value Type, then it’s very easy to understand the difference between classes and structs because this is the main and first difference in both.
Let's understand with a simple example Reference Type and Value Type:
Basically, structures are Value Type and classes are Reference Type, when we said reference type it shows from the name of this concept.
Reference Type is a reference to some location in the memory and if there is any change in a reference type or class object then it will be reflected on all instances of that object because it’s going to update the referred memory location not specific value on a single position. have a look on below example:

        Class Vehicle
    {
        Public Int NoOfTyres;     
    }


when we will use this class, and create an instance of this class then it will allocate the memory for this instance of this class type and will store the address of memory the class.

        Vehicle Vehicle_car1 =new Vehicle();
    Vehicle_obj1.NoOfTyres=4;
    Vehicle Vehicle_car2 =Vehicle_car1;
    Vehicle_car2.NoOfTyres=6;


In this example, we can check both instances of Vehicle class belong to same memory location because we assign Vehicle_car1 to Vehicle_car2 so they have same location. it also indicates that if there is any change in one it will update both because they both have same reference of memory.
As we update the value of second object Vehicle_car2.NoOfTyres=6; it will set both instances to 6. basically, we are getting NoOfTyres of an object by using different pointers.
But Structures are value type as we discuss earlier,
if we take same example,

        Structure Struct_Vehicle
    {
        Public Int NoOfTyres;     
    }
    
    Struct_Vehicle Str_Car1 =new Struct_Vehicle();
    Str_Car1.NoOfTyres=4;
    Struct_Vehicle Str_Car2 =Str_Car1;
    Str_Car2.NoOfTyres=6;


As per Value type when we create different instance and assign the first to second one then it will make copy of first and assign to second it will not refer to same location in memory. so, by updating the second it will not affect first's value and vice versa.
Value Type always contains a value and reference type can have null reference means it does not refer to anything.
Class also support the inheritance but struct does not.
Classes may have parameter less constructor but struct does not.
Structure cannot have destructors but a class can have a destructor.
Struct are in real an actual value and these can be empty but not null whereas class be referred to null.
Struct are best to use on small data of related groups.
Please share your suggestions and feel free to comments.

No comments:

Post a Comment