2

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.

Knitschi
  • 2,822
  • 3
  • 32
  • 51

3 Answers3

6

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

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
Shadowed
  • 956
  • 7
  • 19
  • So I can be sure that the destructor of an object of class type is only called once no matter what I do with it? – Knitschi Jan 27 '16 at 13:45
  • 1
    @Knitschi - C# objects don't have destructors. The nearest thing is finalisers, which most classes don't define either. – Lee Jan 27 '16 at 13:48
  • I vote this as the answer, but want to point out that you can copy objects using serialization, e.g. using Json.Net: `foo f2 = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(f1));` That's clearly outside the scope of the question; I mention it just for the sake of curiosity. – Matthew Watson Jan 27 '16 at 13:50
  • Ok my comment was stupid. Each object can only be destroyed once. – Knitschi Jan 27 '16 at 13:52
  • Destructor is called only by Garbage Collector when object is destroyed by GC. But, if you have inherited class and both it and base class have destructor, they will both be called. Check https://msdn.microsoft.com/en-us/library/66x5fx1b.aspx for details. – Shadowed Jan 27 '16 at 13:53
1

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.

Peter Waher
  • 178
  • 1
  • 8
1

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.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111