Skip to content

Instantly share code, notes, and snippets.

@dnasca
Last active August 29, 2015 14:17
Show Gist options
  • Save dnasca/5a87ce3c57d7f48c9664 to your computer and use it in GitHub Desktop.
Save dnasca/5a87ce3c57d7f48c9664 to your computer and use it in GitHub Desktop.
using System;
/* //Differences between Classes and Stucts//
*
* A Struct is a VALUE TYPE -- it is stored on the stack
*
* A Class is a REFERENCE TYPE -- it is stored on the heap
*
* VALUE TYPES hold their value in memory where they are declared
* REFERENCE TYPES hold a reference to an object in memory
*
* VALUE TYPES are destroyed immediately after the scope is lost
* REFERENCE TYPES -- only the reference variable is destroyed after scope is lost
* + The object is later destroyed by garbage collection
*
* When you copy a struct into another struct, the new copy of that strut gets created and
* modifications on one struct will not affect the values contained by the other struct
*
* When you copy a class into another class, you only get a copy of the reference variable.
* Both reference values point to the same object on the heap.
* In other words, operations on one variable will affect the values contained by the other reference variable
*
*/
public class MyName
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Program
{
public static void Main()
{
//VALUE TYPES - operations on the value of 'y' WILL NOT affect the value of 'x'
int x = 1;
int y = x;
y = y + 1;
Console.WriteLine("x = {0}", x);
Console.WriteLine("y = {0}", y);
//REFERENCE TYPE -- operations on the value of 'a' WILL affect the value of 'b'
MyName a = new MyName();
a.FirstName = "Derrik";
a.LastName = "Nasca";
MyName b = a; //This will create another object reference variable to the SAME OBJECT on the heap
b.FirstName = "Anthony"; //remember, b is NOT a new object, it is simply a reference to the object reference variable 'a'
//therefor, b.FirstName will do exactly the same thing as a.FirstName
//Important Note: While objects reside on the Heap, the object reference variables exist on the stack
Console.WriteLine(a.FirstName);
Console.WriteLine(b.LastName);
Console.ReadKey();
}
}
/* //Some final notes about Structs//
*
* Structs cannot have destructors
*
* Structs can't inheret from another class, but can inherit from an interface
*
* Structs cannot have explicit parameter-less constructors
*
* Structs are sealed types
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment