The code below shows a sample that I've used recently to explain the different behaviour of structs and classes to someone brand new to development. Is there a better way of doing so? (Yes - the code uses public fields - that's purely for brevity)
namespace StructsVsClasses
{
class Program
{
static void Main(string[] args)
{
sampleStruct struct1 = new sampleStruct();
struct1.IntegerValue = 3;
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
sampleStruct struct2 = struct1;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
struct1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
sampleClass class1 = new sampleClass();
class1.IntegerValue = 3;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
sampleClass class2 = class1;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
class1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
Console.ReadKey();
}
}
struct sampleStruct
{
public int IntegerValue;
}
class sampleClass
{
public int IntegerValue;
}
}