[.net] Simple C# Question

Started by
2 comments, last by Striken 16 years, 2 months ago
Hi - learning C# development in the .NET framework but one thing I'm unsure of:

static Main() {
  Bar class1 = new Bar();
  Foo class2 = new Foo(ref class1);
}

public class Bar {
  public Bar() {
  }
}

public class Foo {
  public Foo(ref Bar inClass) {
    _storedClass = inClass;
  }

  private Bar _storedClass;
}








My question is this - is the private _storedClass variable storing a reference or a copy of a? I *thought* (coming from a C++ programmer's point of view) it would copy construct a new object of type Foo and copy the contents across... however I'm using a graphical mapping component control and it seems to be a reference, as any subsequent calls to the stored class appear to be making a visible effect on screen (ie. the original map). I was worried it would be creating new instances of the graphical map every time this operation was performed, however memory and frame rate seem unaffected. I am a little bit confused. Clarification very much appreciated - lack of pointers is confusing me!
- Teach a programmer an answer, he can code for a day. Show a programmer the documentation, he can code for a lifetime.
Advertisement
_storedClass is a reference to an instance of the class Bar.

In c# there's reference types, and value types. Classes are always reference, while structs are always value. When assigning one class instance to another, only the reference is transfered (so both point to the same instance). When assigning two structs to each other, their data is copied over and you now have two copies.

So, your Foo class constructor doesn't need to use the ref keyword. Bar is a class, so will always be passed by reference anyways. Use the ref keyword to force a struct to be passed to a function as a reference. Then you can alter the contents of the original struct within the function, instead of the function just altering a copy of it.
Conceptually, C# classes will behave like C++ smart pointers. If you make a new one, it's new. When you assign one to another, they share the reference. When all the references go away, the instance will be cleaned up automatically.

C# structs/ValueTypes (which includes the numeric primitives) are similar, except copied on assignment.
Great, cheers guys I understand perfectly.
- Teach a programmer an answer, he can code for a day. Show a programmer the documentation, he can code for a lifetime.

This topic is closed to new replies.

Advertisement