C# structs are derived from System.ValueType which overrides the virtual methods in System.Object to use value-based semanitcs instead of reference-based ones.
System.ValueType is allocated on stack rather than on garbage-collected heap. Its lifetime is in the defining scope. Once it runs out of the defining scope, it is popped off the stack. Game over!
int type is a System.Int32 structure.
By default, when a value type contains other reference types (e.g. a struct contains a class), assignment results in a copy of the references (shallow copy).
If a reference type is passed by reference (using ref, the reference is copied by reference), the called method may change the values of the state data and the object it is referencing (i.e. reassign it to a different or new object).
But if a reference type is passed by value (without modifier, the reference is copied by value), its state value could be changed but not the object being referenced (meaning it is still pointing to the same object on heap).
namespace ConsoleApp11
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public void Display()
{
Console.WriteLine($"{Name} {Age}");
}
}
}
namespace ConsoleApp11
{
public static class Common
{
public static void ChangePerson(ref Person p)
{
p.Age = 100;
p = new Person("Cici", 25);
}
public static void ChangePerson(Person p)
{
p.Age = 99;
p = new Person("Lily", 35);
}
}
}
using ConsoleApp11;
using static ConsoleApp11.Common;
Person p1 = new Person("Mike", 80);
Console.WriteLine("Original person");
p1.Display();
ChangePerson(p1);
Console.WriteLine("After being passed by value");
p1.Display();
ChangePerson(ref p1);
Console.WriteLine("After being passed by reference");
p1.Display();
Console.ReadLine();
// result:
// Original person
// Mike 80
// After being passed by value
// Mike 99
// After being passed by reference
// Cici 25
Both value types and reference types can implement interfaces, support fields, method, overloaded operators, constants, properties, and events.