Miyamoto Musashi
Miyamoto Musashi

Reputation: 31

C# return type of function

What does GetNode return, a copy or a reference to the real value?

public GraphNode GetNode(int idx)
{
    return Nodes[idx];
}

In other words will this code change the real value or it will change a copy returned from GetNode?

GetNode(someIndex).ExtraInfo = something;

Thanks

Upvotes: 0

Views: 315

Answers (5)

BrokenGlass
BrokenGlass

Reputation: 161012

In other words will this code change the real value or it will change a copy returned from GetNode?

GetNode(someIndex).ExtraInfo = something;

If GetNode() returns a struct / value type you will actually get a compilation error in C#:

Cannot modify the return value of 'GetNode(someIndex)' because it is not a variable

This is exactly because the compiler is trying to protect you from changing a copied value that goes nowhere. Your example makes only sense if GetNode() returns a reference type.

The only way to get the example to compile for a value type is by separating retrieval of the return value from the property assignment:

var node = GetNode(someIndex);
node.ExtraInfo = something;

In this case as other posters have mentioned it does depend on whether GetNode() returns a reference type or a value type. For a reference type you are changing the original class instance that GetNode() returns a reference to, for a value type you are modifying a new, copied instance.

Upvotes: 1

poupou
poupou

Reputation: 43553

It depends on your definition of GraphNode.

If it is a class (by reference) it will return the same instance;

or if it is a struct (value-type) then you'll get a new instance.

Upvotes: 3

Tony The Lion
Tony The Lion

Reputation: 63310

It will return a reference (in case GraphNode is a class) to a GraphNode object, so the original object will be altered.

Upvotes: 0

xthexder
xthexder

Reputation: 1565

The way classes work in C# is that they can be passed around as pointers.

You can set the values inside it, like you have in your example, and it will change the original. Setting the actual class itself cannot be done without a wrapper though.

Upvotes: 0

Ilia G
Ilia G

Reputation: 10221

Depending on wherever GraphNode is a class or struct. In case of a class you'll be changing "real" value. Struct is the opposite.

Upvotes: 5

Related Questions