Store a reference to an object

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


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.


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.

Tags:

C#

C++