Suppose this is our class Person, having an string property name FullName.
{
public string FullName { get; set; }
}
private void button1_Click(object sender, RoutedEventArgs e)
{
UnderstandingPassbyValandRef();
}
private void UnderstandingPassbyValandRef()
{
Person myPOriginal = new Person();
myPOriginal.FullName = "Nishant Rana";
PassByValue(myPOriginal);
MessageBox.Show(myPOriginal.FullName);
// Output : “Nishant Rana PassByVal”
PassByRef(ref myPOriginal);
MessageBox.Show(myPOriginal.FullName);
// Output : “Srihari Radhakrishnan”
this.Close();
}
-
Here copy of the reference, which points to myPOriginal is passed to the method.So it is possible for the method to change the contents of Person.
-
However by using the new operator inside the method makes the variable pVal reference a new Person object. Thus any changes after that will not affect the orignal person myPOriginal object.
-
private void PassByValue(Person pVal)
{
pVal.FullName = "Nishant Rana PassByVal";
pVal = new Person();
pVal.FullName = "Arvind Singh";
}
- Here actual reference is passed to the method.
- All of the changes that take place inside the method affect the original person object.
- private void PassByRef(ref Person pRef)
{
pRef.FullName = "Nishant Rana PassByRef";
pRef = new Person();
pRef.FullName = "Srihari Radhakrishnan";
}
Bye..
Discover more from Nishant Rana's Weblog
Subscribe to get the latest posts sent to your email.
