Jump to content
  • Advertisement
Sign in to follow this  
Striken

[.net] Simple C# Question

This topic is 3804 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
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.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!