I have some confusion with reference type following is the test example
please tell me how it will works
class TestClass
{
public int i = 100;
}
class MyTestClass
{
public void Method()
{
int i = 200;
var testClass = new TestClass();
testClass.i = 300;
Another(testClass, i);
Console.WriteLine("Method 1:" + testClass.i);
Console.WriteLine("Method 2:" + i);
}
public void Another(TestClass testClass, int i)
{
i = 400;
testClass.i = 500;
testClass = new TestClass();
//If we have set here again testClass.i = 600; what should be out putin this case
Console.WriteLine("Another 1:" + testClass.i);
Console.WriteLine("Another 2:" + i);
}
public static void Main()
{
MyTestClass test = new MyTestClass();
test.Method();
Console.ReadLine();
}
}
***EDIT******
What should be the Output of this,and how many times the Object of the TestClass() will created during execution.
In C# anything that is a struct is a value type, anything that is a class is a reference type. When you pass a value type as a parameter to another method there is no way for the method to alter the original value (unless the value type is passed using the ref keyword). When you pass a reference type as a parameter to another method method any changes the method makes to the object will be reflected in the object upon return from the method. The output would be:
Another 1:100
Another 2:400
Method 1:500
Method 2:200
The i variable in the Another method cannot change the value of the variable i in the Method method, because i is a value type; therefore the value of i in Method (200) is unchanged by your call to Another.
TestClass however is a reference type, so Another can alter the field within it, hence in the line:
changes the value as seen by Method, hence the output of Method 1:500. When you allocate a new instance of TestClass in the line:
testClass = new TestClass();
you have changed what the reference is within Another, but the original instance from Method is no longer available to the method Another, hence anything that another does to its testClass variable will have no impact on the instance the Method is referring to