Skip to content

Instantly share code, notes, and snippets.

@sir-hc-daudore
Last active August 6, 2021 19:55
Show Gist options
  • Save sir-hc-daudore/3c81a67a3578220371174155e004aa16 to your computer and use it in GitHub Desktop.
Save sir-hc-daudore/3c81a67a3578220371174155e004aa16 to your computer and use it in GitHub Desktop.
ref and structs modification example
// For more info on how to use ref keywords for modifying structs
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref
using System;
class MainClass {
public class MyClass {
public float number = 0;
}
// Structs can't be initialized
public struct MyStruct {
public float number;
}
// Class instances are passed as reference value, so they are mutable within the function context
// and changes propagate to the original object
public static void AddToClass(MyClass thing){
thing.number++;
}
// Struct instances are passed as new values, so they are immutable and changes do not propagate
// to the original object
public static void AddToStructNoRef(MyStruct thing) {
thing.number++;
}
// ref keyword allows structs to be passed as reference value instead, allowing mutability of the
// original object
public static void AddToStructWithRef(ref MyStruct thing) {
thing.number++;
}
public static void Main (string[] args) {
MyClass myInstance = new MyClass();
MyStruct myThing = new MyStruct();
Console.WriteLine ("myInstance.number before adding = " + myInstance.number);
AddToClass(myInstance);
Console.WriteLine ("myInstance.number after adding = " + myInstance.number);
Console.WriteLine ("myThing.number before adding without ref = " + myThing.number);
AddToStructNoRef(myThing);
Console.WriteLine ("myThing.number after adding without ref = " + myThing.number);
// ref keyword is used to indicate that the struct instance is passed as reference value
AddToStructWithRef(ref myThing);
Console.WriteLine ("myInstance.number after adding with ref = " + myInstance.number);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment