Is it possible to make an noncopyable type in C#

873 Views Asked by At

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.

3

There are 3 best solutions below

5
On BEST ANSWER

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".

0
On

You could create an internal constructor. That way, the constructor can only be called from the assembly in which it is defined.

You can also create more advanced logic through the use of Reflection and StackTrace (for instance) and in detail control who is allowed to create instances of the class, and when. Similar logic can be applied to properties, where you can control who is allowed to change property values.

0
On

There is no such thing as a destructor in C#, only Finalizers. However the GC is smart enough to know when no more rerfences exist for a given object and than calls this finalizer. Thus when two variables reference the same object this object lives as long as those two references exist. If both (!!) are out of scope GC collects the object for deleting.