·  C# - Syntax - Collections - Struct

 

- Info:

  - Main differences between Class and Struct is that a Class is a reference type and a Struct is a value type.

  - You should avoid using pointers and structs unless performance is priority.

  - This tutorial is based on:

    http://www.johnnycantcode.com/post/Csharp-Classes-vs-Structs.aspx

    http://msdn.microsoft.com/en-us/library/aa288471(VS.71).aspx

 

- Stack:

  - Stack is a simple FILO-First In Last Out memory structure.

  - During method execution data is being dumped into the stack.

  - When program exists the method, all that data is removed from stack returning it into previous state.

  - Only value types are stored in the stack, as a single space in memory.

  - References to objects, structs and all of the primitive types such as int, bool, decimal etc. are value types.

 

- Heap:

  - Heap is random access memory structure.

  - Objects are allocated and deallocated in a random order.

  - Heap requires the use of a "memory manager" and "garbage collector" to maintain it's structure.

  - When you instantiate a class, object is stored in the heap and reference to object is stored in the stack.

    Form f1 = new Form();

 

- Example:

  - Struct sc2 is an independent copy of sc1 so changing property of sc2 doesn't effect that property in sc1.

  - cc2 is a copy of the refence to cc1 therefor cc1 and cc2 are both references to the same object in memory.

    Changing property of cc2 also changes property of cc1.

  - Create C# Console Application Test.cs.

 

    Test.cs

    using System;

   

    class Class_Circle {

      public int    r=5;

      double getScope() { return 2*r*3.14; }

    }

   

    struct Struct_Circle {

      public int    r;

      double getScope() { return 2*r*3.14; }

    }

   

    class Test {

   

      static void Main(string[] args) {   

   

        //CLASS.

        Class_Circle  cc1   = new Class_Circle();       

        Class_Circle  cc2   = cc1;  //cc1 and cc2 are references pointing to the same object.

                      cc2.r = 10;   //Changes in cc2 influence cc1.

        Console.WriteLine(cc1.r);   //Changed to 10.

   

        //STRUCT.

        Struct_Circle sc1   = new Struct_Circle();    

                      sc1.r = 5;

        Struct_Circle sc2   = sc1;  //sc1 and sc2 are independed copies of struct value type.

                      sc2.r = 10;   //Changes in sc2 don't influence sc1.

        Console.WriteLine(sc1.r);   //Remains 5.

   

      }

   

    }