Search code examples
c#noncopyable

Is it possible to make an noncopyable type in C#


Is it somehow possible in C# to create a class that can not be copied around but rather can only be passed around by reference?

The equivalent in C++ would be to delete the copy-constructor and the copy-assignment operator.


Solution

  • It is default behavior. If you have class:

    class foo {
        public string bar { get; set; }
    }
    

    and somewhere you do this:

    foo f1 = new foo();
    foo f2 = f1;
    

    Both f1 and f2 will reference same instance. If you, for example, set f1.bar = "bar", value read from f2.bar will be "bar".