Reader Level:
ARTICLE

Some Real Differences Between Structures and Classes

On March 02, 2009 Articles | Coding Best Practices
This article lists some differences between classes and structures.
  • 1
  • 0
  • 97441

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.

Good Dotneting!!!

Article Extensions
Contents added by Manas Ranjan Das on Oct 15, 2011
 

Difference between structure and class



This is important question that several people ask in forums and in Interview “what is difference between structure and class?

there many difference between struct and class

1)The structures are value types and the classes are reference types.So object of structure store in stack exactly like any other value type like an Integer, a double but object of class store in heap.Your can assigned null to class variable but you can't assigned null value to structure variable

2)Class support Inheritance but struct does not support so access modifier of a member of a struct cannot be protected or protected internal

3)You can use Destructor in a class but You can use it in a structure

4)When passing a class to a method, it is passed by reference. When passing a struct to a method, it's passed by value instead of as a reference.

5)Structs cannot contain explicit parameterless constructors but You can create in class

like

struct a

{

int result;

public b()//it is possible in class, no error will come

{

result = 5;

}

}

struct a

{

int result;

public b()//it is not possible struct,compile error will come

{

result = 5;

}

}



6)You can instance Field initializer of class but You can't do in structs

for example

class emp

{

public string name = "cheater"; //No synstax error

}

struct emp

{

public string name="cheater"; //No synstax error will come

}



7)structures can not be garbage collector so no memory management.

classes can be garbage collector because garbage collector works on heap memory

Bechir Bejaoui

The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  ...

  • 33rank
  • 3M readers
  • 1times
COMMENT USING

Trending up