Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store a reference to an object

Tags:

c++

c#

A bit of a weird question but I was wondering anyone could help...

In C++, I could do something like this

class MyOtherClass
{
     private:
         MyLogger* logger;
     public:
         MyOtherClass (MyLogger* logger)
              : logger (logger)
         {}
};

class MyClass
{
     private:
         MyLogger* logger;
     public:
         MyClass (MyLogger* logger)
              : logger (logger)
         {}
};

int main (int c, char** args)
{
    MyLogger* logger = new MyLogger ();
    /* Code to set up logger */
    MyOtherClass* myOtherClass = new MyOtherClass (logger);
    MyClass* myClass = new MyClass (logger);
}

So that each of the other objects (myOtherClass and myClass) would contain a pointer to logger, so they would be calling the same logger class. However, how would I achieve the same thing in C#? Is there a way to store a reference or pointer to a global object - I'm guessing that in C# if I do something like

public class MyClass
{
     private MyLogger logger = null;

     public MyClass (MyLogger _logger)
     {
         logger = _logger;
     }
};

that its actually assigning the class variable logger to a copy of _logger? Or am I'm mixing things up :S

Any help is very much appreciated, and thank you in advance!

like image 566
KingTravisG Avatar asked Nov 08 '12 16:11

KingTravisG


3 Answers

It's actually a lot simpler in C#.

Basically, you can do this:

MyLogger logger = new MyLogger();
MyOtherClass myOtherClass = new MyOtherClass(logger);
MyClass myClass = new MyClass(logger);

In C#, the classes are basically kept around as references (really just pointers under the hood). In this snippet, you are passing the reference to logger to the constructors of both objects. That reference is the same, so each instance has the same MyLogger instance.

In this particular instance, you pretty much just need to remove the pointer syntax =D

like image 51
Tejs Avatar answered Oct 05 '22 01:10

Tejs


You're mixing things up. In C#, assignment statements such as

    logger = _logger;

copy references, not objects. After this statement executes, there is still (at most) only one MyLogger - it's now referred to by two object variables.

like image 36
AakashM Avatar answered Oct 04 '22 23:10

AakashM


If the type is a reference type (which is the case for classes), then you will copy the reference, not the object itself.

In opposition to reference type, you have value types. Values types are basically basic types : int, double, etc,

In your case, that means that you will work with the same objects, whether you access it from the class, or from the outer calling method. It's because you are targeting the referenced object.

like image 22
3 revs Avatar answered Oct 05 '22 01:10

3 revs