Monday, 3 August 2015

Difference between a structure and a class

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:
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

  1. Classes are usually used for large amounts of data, whereas structs are usually used for smaller amounts of data.
  2. Classes can be inherited whereas structures not.
  3. A structure couldn't be null like a class.
  4. A structure couldn't have a destructor such as a class.
  5. A structure can't be abstract, a class can.
  6. 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.
 
  1. 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.
  2. 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{
         }


9.     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();
        }
    }
 
  1. The strucutre can't conatain a volatile field whereas the class can
  2. You can't use sizeof with classes but you can with structures
  3. Fields are automatically initialized with classes to 0/false/null wheatheras strucutres are not
  4. 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
        }
     
  5. 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





No comments:

Post a Comment