Skip to content

Instantly share code, notes, and snippets.

@tsraveling
Created June 17, 2021 23:29
Show Gist options
  • Save tsraveling/bf4f1d5a790c57d9445b568915dd3d4d to your computer and use it in GitHub Desktop.
Save tsraveling/bf4f1d5a790c57d9445b568915dd3d4d to your computer and use it in GitHub Desktop.
C# Reference vs Value

This file:

namespace Dev.Sandbox
{
    public class DevExampleClass
    {
        public string first;
        public string last;

        public DevExampleClass(string first, string last) {
            this.first = first;
            this.last = last;
        }
    }

    public struct DevExampleStruct
    {
        public string first;
        public string last;
        
        public DevExampleStruct(string first, string last) {
            this.first = first;
            this.last = last;
        }
    }
    
    public static class DevScriptSandbox
    {
        public static void TestReferenceValue() {
            
            var classOb = new DevExampleClass("Alice", "Adams");
            var structOb = new DevExampleStruct("Bob", "Barker");

            Debug.Log("Initial review: class is " + classOb.first + " " + classOb.last + ", and struct is " + structOb.first + " " + structOb.last);

            var classCopy = classOb;
            var structCopy = structOb;

            classCopy.last = "Mephistopheles";
            structCopy.last = "Beelzebub";
            
            Debug.Log("Copies: class is " + classCopy.first + " " + classCopy.last + ", and struct is " + structCopy.first + " " + structCopy.last);
            Debug.Log("Originals: class is " + classOb.first + " " + classOb.last + ", and struct is " + structOb.first + " " + structOb.last);
        }
    }
}

Ouputs:

Initial review: class is Alice Adams, and struct is Bob Barker
UnityEngine.Debug:Log(Object)
Dev.Sandbox.DevScriptSandbox:TestReferenceValue() (at Assets/Dev/Sandbox/DevScriptSandbox.cs:34)
Dev.StateTools.DevJumpstarter:DevStartCampus() (at Assets/Dev/StateTools/DevJumpstarter.cs:14)
Dev.Components.DevGameManager:Start() (at Assets/Dev/Components/DevGameManager.cs:11)

Copies: class is Alice Mephistopheles, and struct is Bob Beelzebub
UnityEngine.Debug:Log(Object)
Dev.Sandbox.DevScriptSandbox:TestReferenceValue() (at Assets/Dev/Sandbox/DevScriptSandbox.cs:42)
Dev.StateTools.DevJumpstarter:DevStartCampus() (at Assets/Dev/StateTools/DevJumpstarter.cs:14)
Dev.Components.DevGameManager:Start() (at Assets/Dev/Components/DevGameManager.cs:11)

Originals: class is Alice Mephistopheles, and struct is Bob Barker
UnityEngine.Debug:Log(Object)
Dev.Sandbox.DevScriptSandbox:TestReferenceValue() (at Assets/Dev/Sandbox/DevScriptSandbox.cs:43)
Dev.StateTools.DevJumpstarter:DevStartCampus() (at Assets/Dev/StateTools/DevJumpstarter.cs:14)
Dev.Components.DevGameManager:Start() (at Assets/Dev/Components/DevGameManager.cs:11)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment