dlanod
dlanod

Reputation: 8980

C#: Returning a reference?

I'm attempting to cache a proxy in a C# WCF program so I don't need to create it each time I process a message for a different client, so my aim is to write a function that returns a reference to the proxy.

I'm not fully conversant with C#'s return mechanisms versus "out" parameters versus "ref" parameters yet though, so was wondering if this will result in a reference to _interface being returned, or a copy, or some other behaviour.

        public IInterface GetInterface
        {
            return _interface;
        }

Upvotes: 0

Views: 281

Answers (3)

Ed Swangren
Ed Swangren

Reputation: 124642

Classes are reference types. They are implicitly passed around by copy-of-reference. So, you are passing a reference in your example, but you are passing a copy of the reference. This is important to understand if you are passing it to a method that is changing the object that the reference points to on the heap. In that case you are simply pointing the copy to a new object and the original reference will remain unchanged.

On a side note, the purpose of the 'ref' modifier is to pass the actual reference itself, not a copy of said reference.

Upvotes: 1

BoltClock
BoltClock

Reputation: 723598

IInterface is a reference type, so it will return a copy of the reference to the object of which class implements that interface. You're still pointing to the same object, it's just that the calling code obtains a new reference to the same object for its own use.

Upvotes: 2

Heinzi
Heinzi

Reputation: 172260

If concrete type implementing IInterface is in fact a class (as opposed to a struct); then yes, your code will return only a reference to the object. (Otherwise, things are a bit more complicated.)

In fact, when dealing with classes in C#, it's almost impossible to "accidentally" create a copy of the object itself. You'd need to explicitly call some method such as MemberwiseClone or ICloneable.Clone.

Upvotes: 1

Related Questions