Alex
Alex

Reputation: 3968

C# method returns int-by value or reference

I am trying to work out where an int returned by a method will be stored. I assume it is the stack, but want to clarify. The scenario is as follows:

public int returnInt()
{
   var returnVal=1:
   Return returnVal;
}

In this case I know returnVal will be stored on the stack, and will pop when the returnInt method has run. In actual terms, returnVal is a value type, so will not be passed by reference.

The part I am not clear about is as follows:

public void callerMethod()
{
    var intVal=returnInt();
}

What I think happens here is the actual value is returned, and saved in a new memory location on the stack for callerMethod.

Can anyone confirm if this is correct? Please also feel free to correct anything else I have said that is not correct...

Upvotes: 0

Views: 2152

Answers (1)

tmaj
tmaj

Reputation: 35037

The value in callerMethod() is a new value, independent of the value in returnInt().

I hope the example below helps.

static int myStaticInt = 333;
public static int returnInt()
{
    return myStaticInt;
}

public static void callerMethod()
{
    var i = returnInt();
    i += 100;
    Console.WriteLine(i);
}

public async static Task Main(string[] args)
{
    Console.WriteLine(myStaticInt);
    callerMethod();
    Console.WriteLine(myStaticInt);
}

Output

333
433
333

Result

myStaticInt is still 333.


Here is a relevant part from Passing Value-Type Parameters (C# Programming Guide):

A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Passing a value-type variable to a method by value means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the argument variable.

Here is a bit about assignment from Types part of C# specification.

Assignment to a variable of a value type creates a copy of the value being assigned. This differs from assignment to a variable of a reference type, which copies the reference but not the object identified by the reference.


Passing and returning value types by reference

Please note that it is possible to pass, and return, value types by reference.

Please see Passing Value Types by Reference section of Passing Value-Type Parameters (C# Programming Guide) and Ref returns and ref locals.

Equipped with this knowledge, let's now modify our example and examine the result.

static int myStaticInt = 333;
public static ref int returnInt()
{
    //var returnVal = 1;
    return ref myStaticInt;
}

public static void callerMethod()
{
    ref var i = ref returnInt();
    i += 100;
    Console.WriteLine(i);
}

public async static Task Main(string[] args)
{
    Console.WriteLine(myStaticInt);
    callerMethod();
    Console.WriteLine(myStaticInt);
}

Output

333
433
433

Result

myStaticInt is now 433, not the original 333.

Upvotes: 1

Related Questions