I defined a simple class with the following definition. In this sample, I defined a simple class with a single string parameter. Then I instantiated this class and assigned a value to the parameter. I passed that instance to another function without specifying "ref" keyword. It means it should be passed by value instead of reference. But what I don't understand is the reason that the output displays "Second Modification" value as a result instead of "First Modification".
UPDATE 1:
I think my question was confusing. I know how "ref" and "pass by reference" working. I need to know why when I "pass by value", run-time still changes the value of the original instance. By the way, I couldn't find my answer in the proposed links.
UPDATE 2:
I asked this question two years ago. Now I understand all properties of an object (instance of a class) are reference type. It means when I pass an instance of a class to another method, they all behave as a reference to original member of the class.
public class MyClass
{
public String TestProperty { get; set; }
}
public class TestClass
{
public TestClass()
{
var myClass = new MyClass();
myClass.TestProperty = "First Modification";
MyFunction(myClass);
Console.WriteLine(myClass.TestProperty); // Output: "Second Modification"
}
void MyFunction(MyClass myClass)
{
myClass.TestProperty = "Second Modification";
}
}
That is the expected behavior. What ref would allow you to do is create a new object in MyFunction and assign it to the myClass parameter and have the new object available outside the method.
Have a look at http://msdn.microsoft.com/en-us/library/14akc2c7.aspx for more details.
You can change the object passed to the method, but you can't change the reference itself without the
ref
keywordIf you want to prevent the property being changed, you can make the setter non-public: