简体   繁体   中英

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

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

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.

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.

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.

它将返回对GraphNode对象的引用(如果GraphNode是类),因此将更改原始对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM