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
.