Wednesday, June 15, 2011

Difference between Class and Structures in C#

Hi! It's me again, Eric and now i would to differentiate classes and structures in C#.
So let us define what are classes and structures first. Class are set of data that can be inherit. They can be declared using the keyword class. They are surrounded by curly braces and each of it have constructors. On the other hand, Structures are quite similar to classes but have some restriction.

Differences:
a.) Classes can be inherited, while Structures cannot.
b.) You can initialize objects in class, while on structures you either use a constructor in initializing variables.
c.) Structure can't have a default parameter-less constructor or destructor.

Have a look at my sample:

using System;


namespace StructureVsClassConsoleBlog
{
    // Class
    class Program
    {
        int intVariable;
        int intVariable2 = 20; // You can initialize a value here.


        public Program()
        {
            this.intVariable = 28; // My birthday! :@)
        }


        public static void Main()
        {
            // Calling the class.
            Program program = new Program();
            // Calling the structure.
            SampleStructure structure = new SampleStructure(14);
            Console.WriteLine(structure.intStructVariable);
            structure.intStructVariable = 1;
            Console.WriteLine(program.intVariable);
            Console.WriteLine(structure.intStructVariable);
            structure.StructureMethod();


            Console.ReadKey();
        }
    }


    // Structures
    struct SampleStructure
    {
        public int intStructVariable; // Cannot be initialize here.


        public SampleStructure(int number)
        {
            this.intStructVariable = number;
        }


        public void StructureMethod()
        {
            Console.WriteLine("This is inside the StructureMethod().");
        }
    }
}


Result:
14                                                               
28                                                              
1                                                                 
This is inside the StructureMethod(). 

Sorry guys, i'm a little bit tired in changing the colors of my code.
Have fun! :@)

No comments:

Post a Comment