Passing Reference Type by Reference

Suppose this is our class Person, having an string property name FullName.

        class Person
        {
            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..


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s