In this small piece of code, changing a 2 dimensional array inside a method leads to changes the variable in main method.
What is the cause of this and how can I protect the variable in main method to remain unchanged?
using System;
namespace example
{
class Program
{
static void Main(string[] args)
{
string[,] string_variable = new string[1, 1];
string_variable[0, 0] = "unchanged";
Console.Write("Before calling the method string variable is {0}.\n", string_variable[0,0]);
Function(string_variable);
Console.Write("Why after calling the method string variable is {0}? I want it remain unchanged.\n", string_variable[0, 0]);
Console.ReadKey();
}
private static void Function(string [,] method_var)
{
method_var[0, 0] ="changed";
Console.Write("Inside the method string variable is {0}.\n", method_var[0, 0]);
}
}
}
At the end this is the program output:
Before calling the method string variable is unchanged.
Inside the method string variable is changed.
Why after calling the method string variable is changed? I want it remain unchanged.
EDIT 1: A question come in my mind is : What are other common programming languages that doesn't have this sort of problem?
EDIT 2: For sack of comparison, I write this somehow identical code with string variable instead of array and the output is as expected and is just fine:
using System;
namespace example
{
class Program
{
static void Main(string[] args)
{
string string_variable;
string_variable= "unchanged";
Console.Write("Before calling the method string variable is {0}.\n", string_variable);
Function(string_variable);
Console.Write("after calling the method string variable is {0} as expected.\n", string_variable);
Console.ReadKey();
}
private static void Function(string method_var)
{
method_var ="changed";
Console.Write("Inside the method string variable is {0}.\n", method_var);
}
}
}
and the output of this code is :
Before calling the method string variable is unchanged.
Inside the method string variable is changed.
after calling the method string variable is unchanged as expected.
Last EDIT : Thanks everybody for clarification, Hope this will become useful for others in future.