Sunday, June 16, 2013

Struct and Class Example | Difference Between Struct and Class

Structs and Class:

struct class
1 It is value type It is Reference Type
2 Default access specifier is Public Default access specifier is Private
3 It only has Constructor It has both Constructor and Destructor
4 Struct has values residing on Stack  Class have Object values residing on Heap and it has references to the objects on stack
5 do not support Inheritance It Supports Inheritance

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    struct emp
    {
        public int empid;
        public string empname;
    }

    class dept
    {
        public int deptid;
        public string deptname;
    }

    class Program
    {
        static void Main(string[] args)
        {
            emp e = new emp();
            emp e2 = e;

            e.empid = 1;
            e.empname = "chandan";

            e2.empid = 2;
            e2.empname = "Rahul";

            Console.WriteLine("ID:{0} and Name:{1}", e.empid, e.empname);
            Console.WriteLine("ID2:{0} and Name2:{1}", e2.empid, e2.empname);

            dept d = new dept();
            dept d2 = d;

            d.deptid = 100;
            d.deptname = "Accounts";

            d2.deptid = 101;
            d2.deptname = "IT";

            Console.WriteLine("ID:{0} and Name:{1}", d.deptid, d.deptname);
            Console.WriteLine("ID2:{0} and Name2:{1}", d2.deptid, d2.deptname);

            Console.ReadLine();
        }
    }
}

Result :

class object referring to the same values whereas struct has new values assigned


No comments:

Post a Comment