rocklobster
rocklobster

Reputation: 619

Setting a member variable to an object outside the class

I want to track a variable in my class that was created outside the scope. In C++ i'd just pass a pointer like this.

class Camera
{
    Player* player;
    Position pos;

    void setFollow(Player* pl) { pl = player; }
    void update() { pos = pl->getPos(); }
}

int Main()
{
    Camera* camera = new Camera();

    Player* player = new Player();

    camera->setFollow(player);
}

In C# I tried to pass by reference but it didnt seem to work.

public class Game1 : Microsoft.Xna.Framework.Game
{
    Camera cam = new Camera();
    Player player = new Player();

    cam.setFollow(ref player);  // <-- by reference
}

This is just a shortened version of my actual code.

Thanks for any help.

EDIT: Thanks to all for the information.

Upvotes: 0

Views: 1982

Answers (5)

Lukasz Madon
Lukasz Madon

Reputation: 14994

ref keyword in C# has a really bad name. It doesn't mean you pass by reference! It should have been named alias, because this is the good word that describes the semantic of ref.

// here I assign a reference(another bad name :) )
// you can also call it Garbage Collector Handler 
// of type Player with a new object
Player player = new Player(); 
// ref means that player is the same thing that parameter pl of setFollow
cam.setFollow(ref player); 

More details

Upvotes: 0

Dan Puzey
Dan Puzey

Reputation: 34200

In C#, object (class) variables are implicitly pointers. So, if your class Camera has a field p of type Player, setting cam.p = player in your code would leave both references pointing to the same instance. There's generally no need to use ref unless you're passing value types (int, float, structs, etc) by reference.

Upvotes: 3

Eric Petroelje
Eric Petroelje

Reputation: 60498

There should be no need to use the ref keyword here as objects are always passed by reference in C#. The ref keyword in C# is typically used more like a pointer-to-a-pointer (**) would be used in C/C++

Upvotes: 1

Bob Vale
Bob Vale

Reputation: 18474

Classes are always passed by reference so you don't need the ref bit that you are trying to do

simply

cam.setFollow(player);

Upvotes: 0

Prabhavith
Prabhavith

Reputation: 486

Player itself is a reference type why are you using ref. You can read more about ref here http://msdn.microsoft.com/en-us/library/14akc2c7.aspx

Upvotes: 0

Related Questions