Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created March 17, 2015 06:42
Show Gist options
  • Select an option

  • Save dnasca/4a79f9de379b6b71c0b2 to your computer and use it in GitHub Desktop.

Select an option

Save dnasca/4a79f9de379b6b71c0b2 to your computer and use it in GitHub Desktop.
Value Types and Reference Types
using System;
/* Differences between Value Types and Reference Types
*
* Value Types:
* All numeric data types
* Boolean, Char, and Date
* All Structures, even if the members of the struct are reference types
* Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong
*
* Reference Types:
* Strings
* All arrays, even if their elements are value types
* Class types
* Delegates
*
* When a value-type instance is created, a single space in memory is allocated to store the value. When the runtime deals with a value type
* it's dealing directory with its underlying data
*
* When a reference-type instance is created, and object is created in memory, and handled through a separate reference (much like a pointer)
*
*/
class FractionClass //reference type
{
public int numerator;
public int denominator;
}
public struct FractionStruct //value type
{
public int numerator;
public int denominator;
}
public class Program
{
static void RefType()
{
FractionClass fc1 = new FractionClass // the reference object fc1 (on the stack) is referencing the Fraction object on the heap
{
numerator = 1,
denominator = 2
};
FractionClass fc2 = fc1; // fc2 only copies a reference to fc1, which will point to the object on the heap
fc2.numerator = 100; // this changes the value on the heap, so any references to fc2 (or fc1) will refer to the same value on the heap
Console.WriteLine(fc1.numerator);
}
static void ValueType()
{
FractionStruct fs1 = new FractionStruct // fs1 and it's values placed directly on the stack. there is nothing on the heap
{
numerator = 2,
denominator = 4
};
FractionStruct fs2 = fs1; // fs2 is now a copy of fs1 (including all it's members)
// fs2 becomes it's own object that carries it's own values. still nothing on the stack.
fs2.numerator = 200; // fs2 is it's own object and contains it's own members. it has no reference to fs1. fs1 and fs2 are seperate objects with seperate members
Console.WriteLine(fs2.numerator);
}
public static void Main()
{
Console.Write("FractionClass numerator: ");
RefType();
Console.Write("FractionStruct numerator: ");
ValueType();
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment