Difference between class and structure

  1. The structures are value types and the classes are reference types.
    namespace DifferenceBetweenClassesAndStructures
        struct StrucutreExample
            public int x;        
        class ClassExample
            public int x;        
        class Program
            static void Main(string[] args)
                StrucutreExample st1 = new StrucutreExample(); // Not necessary, could have done StructureExample1 st1;
                StrucutreExample st2;
                ClassExample cl1 = new ClassExample();
                ClassExample cl2;                        
                cl1.x = 100;
                st1.x = 100;
                cl2 = cl1;
                st2 = st1;
                cl2.x = 50;
                st2.x = 50;
                Console.WriteLine("st1 - {0}, st2 - {1}", st1.x, st2.x);            
                Console.WriteLine("cl1 - {0}, cl2 - {1}", cl1.x, cl2.x);            
    Out put will be as below:
    st1 - 100, st2 - 50 cl1 - 50, cl2 - 50
  2. Object of structure store in stack exactly like any other value type like an Integer, a double but object of class store in heap.
  3. Your can assigned null to class variable but you can't assigned null value to structure variable
  4. Class support Inheritance but struct does not support so access modifier of a member of a struct cannot be protected or protected internal
  5. You can use Destructor in a class but You can use it in a structure
  6. 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.
  7. structures can not be garbage collector so no memory management.
    classes can be garbage collector because garbage collector works on heap memory.


Twitter Delicious Facebook Digg Stumbleupon Favorites More