Sign in to follow this  

[.net] Simple C# Question

This topic is 3592 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


Link to post
Share on other sites
_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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 3592 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this