Thursday, October 1, 2015

Difference Between Structure and class in c#

This blog defines the difference between  Structure and class
Structure
  1. Structure is a value type that is why its object is created on the stack memory.
     
  2. Structure does not support the inheritance.
     
  3. Structure can only have the parametrized constructor. it means a structure can not have the non-parametrized constructor,default constructor and destructor also.
     
  4. The member variable of structure can not be initialized directly.
     
  5. Structure object can be created without using the new keyword.(optional)

    Demo obj;
Class
  1. Class is a reference type and its object is created on the heap memory.
     
  2. Class can inherit the another class.
     
  3. Class can have the all types of constructor and destructor.
     
  4. The member variable of class can be initialized directly.
     
  5. class object can not be created without using the new keyword, it means we have to use it.

    Demo obj=new Demo();
A short summary of each:
Classes Only:
  • Can support inheritance
  • Are reference (pointer) types
  • The reference can be null
  • Have memory overhead per new instance
Structs Only:
  • Cannot support inheritance
  • Are value types
  • Are passed by value (like integers)
  • Cannot have a null reference (unless Nullable is used)
  • Do not have a memory overhead per new instance - unless 'boxed'
Both Classes and Structs:
  • Are compound data types typically used to contain a few variables that have some logical relationship
  • Can contain methods and events
  • Can support interfaces
When to Use Structure and Class?

In general, classes can be used when you have more complex behavior or data. And if you think that these behaviour or data to be modified after creating an instance of class, then classes are absolute methods.
Structures can be used for small data structures. If developer feels that data members of structure cannot to be modified after creating structure, then having structure will suit.

  1. Classes are Reference types and Structures are Values types.When I say Classes are reference types, basically they will contain the address of an instance variables. For example:
    Class MyClass
    {
    Public Int DataMember;  //By default, accessibility of class data members 
       //will be private. So I am making it as Public which 
       //can be accessed out side of the class.
    }
    In main method, I can create an instance of this class using new operator that allocates memory for this class and stores the base address of that into MyClass type variable.
    Static Public void Main (string [] arg)
    {
     MyClass _myClassObject1 =new MyClass ();
     _ myClassObject1.DataMember=10;
     MyClass _myClassObject2 =_myClassObject1;
     _ myClassObject2.DataMember=20;
    }
    In the above program, “MyClass _myClassObject2 =_myClassObject1” instruction indicates that both variables of type MyClass myClassObject1 and myClassObject2 will point to the same memory location. It basically assigns the same memory location into another variable of same type.
    So if any changes that we make in any one of the objects type MyClass will have an effect on another since both are pointing to the same memory location.
    _ myClassObject1.DataMember=10” at this line both the object’s data members will contain the value of 10_ myClassObject2.DataMember=20 at this line both the object’s data member will contains the value of 20. Eventually, we are accessing datamembers of an object through pointers.
    Unlike classes, structures are value types. For example:
    Structure MyStructure
    {
    Public Int DataMember;  //By default, accessibility of Structure data 
       //members will be private. So I am making it as 
       //Public which can be accessed out side of the structure.
    }
    
    Static Public void Main (string [] arg)
     {
     MyStructure _myStructObject1 =new MyStructure ();
     _ myStructObject1.DataMember=10;
     MyStructure _ myStructObject2 =_ myStructObject1;
     _ myStructObject2.DataMember=20;
    }
    In the above program, instantiating the object of MyStructure type using new operator and storing address into _myStructObject variable of type MyStructure and assigning value 10 to data member of the structure using “_ myStructObject1.DataMember=10”. In the next line, I am declaring anothervariable_myStructObject2 of type MyStructure and assigning _myStructObject1 into that. Here .NET C# compiler creates another copy of _myStructureObject1 object and assigns that memory location into MyStructure variable _myStructObject2.
    So whatever change we make on _myStructObject1 will never have an effect on another variable_myStructObject2 of type MyStructrue. So that’s why we are saying Structures are value types.
    So the immediate Base class for class is Object and immediate Base class for Structure is ValueTypewhich inherits from Object.
  2. Classes will support an Inheritance whereas Structures won’t.



Some important questions that people ask in forums is "what's the difference between a structure and a class?" and "what could be the value of a structure since we already have classes that can do the job perfectly?". Those questions could particularly be posed by a Java programmer that wants to migrate from Java to .Net. For this reason I will list in this article some of those differences to make the issue clear.
  1. Structures are value types and the classes are reference types. Before proceeding to the next point, let explain the difference between the two types. Imagine this is the memory within the machine:


    structure

    Figure 1

    The value types are stored in the stack but the reference types are not. In fact, what could be really stored in the stack for the reference types is a pointer that targets an address at the heap level.

    Then the type of structure objects are stored in the stack exactly like any value type, say an integer, a double or a float. Meanwhile, memory locations could be reserved for reference types in the heap. Defining the heap and stack and the difference between them is beyond the scope of this article but nevertheless I propose this excellent Matthew article to understand the memory mechanisms.

    http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91
     
  2. Classes are usually used for large amounts of data, whereas structs are usually used for smaller amounts of data.
  3. Classes can be inherited whereas structures not.
  4. A structure couldn't be null like a class.
  5. A structure couldn't have a destructor such as a class.
  6. A structure can't be abstract, a class can.
  7. You cannot override any methods within a structure except the following belonging to the type object:
     
    • Equals()
    • GetHashCode()
    • GetType()
    • ToString()

    And the other polymorphism technique used for structures is implementing interfaces.
     
  8. Declared events within a class are automatically locked and then they are thread safe, in contrast to the structure type where events can't be locked.
  9. A structure must always have the default parameter less constructor defined as public but a class might have one, so you can't define a private parameter-less constructor as in the following:

    struct Me    {
            private Me()// compile-time error        {
            }
        }
         
    class
     Me         {
                private Me()// runs Ok{
             }

     
  10. A static constructor is triggered in the case of a class but not in the case of a structure as in the following:

    struct myStructure    {
            static myStructure() 
            {
                Console.WriteLine("This is me a structure");
            }
        }
        class myClass
        {
            static myClass()
            {
                Console.WriteLine("This is me a class");
            }
        }
        class Program    {
            static void Main(string[] args)
            {
               myStructure s =new myStructure();//Nothing happen           myClass c =new myClass();//Will out put This is me a class           Console.Read();
            }
        }
     
  11. The strucutre can't conatain a volatile field whereas the class can
  12. You can't use sizeof with classes but you can with structures
  13. Fields are automatically initialized with classes to 0/false/null wheatheras strucutres are not
  14. Fields can't be directley instantiated within structures but classes allow such operations as in the following:

    struct myStructure    {
            publicstring x = 2;//Not allowed     }
        class myClass    {
            publicstring x = 2;//Allowed    }
     
  15. Structures and classes don't adopt the same aproach for the System.Object.Equals() method.

    Assume the following strucutre and class:

    struct StructurePerson    {
            publicstring FirstName;
            publicstring LastName;
        }
        class ClassPerson    {
            publicstring FirstName;
            publicstring LastName;
        }
    Now, try this code:

    class Program    {
            static void Main(string[] args)
            {
                StructurePerson strX =new StructurePerson();
                strX.LastName = "Bejaoui";
                strX.FirstName = "Bechir";
                StructurePerson strY =new StructurePerson();
                strY.LastName = "Bejaoui";
                strY.FirstName = "Bechir";
                if (strX.Equals(strY))
                {
                    Console.WriteLine("strX = strY");
                }
                else            {
                    Console.WriteLine("strX != strY");
                }//This code displays strX = strY
                ClassPerson clsX =new ClassPerson();
                clsX.LastName = "Bejaoui";
                clsX.FirstName = "Bechir";
                ClassPerson clsY =new ClassPerson();
                clsY.LastName = "Bejaoui";
                clsY.FirstName = "Bechir";
                if (clsX.Equals(clsY))
                {
                    Console.WriteLine("clsX = clsY");
                }
                else            {
                    Console.WriteLine("clsX != clsY");
                }//This code displays clsX != clsY            Console.Read();
            }
        }

    In the first strucutre the two objects are value types, they are compared depending on their values like int I = 5 and int J = 5 so I=J because they have the same value. In the contrast, in the class case of two different and distinct references, to make clsX = clsY you should use the following code:

                ClassPerson clsX =new ClassPerson();
                clsX.LastName = "Bejaoui";
                clsX.FirstName = "Bechir";
                ClassPerson clsY = clsX;
                if (clsX.Equals(clsY))
                {
                    Console.WriteLine("clsX = clsY");
                }
                else            {
                    Console.WriteLine("clsX != clsY");
                }//This code displays clsX = clsY


That's it.

No comments:

Post a Comment