Friday 26 February 2021

ref vs Out parameters

 

class Program

    {

        static void Main(string[] args)

        {

            //The ref is a keyword in C# which is used for the passing the arguments by a reference.

            string str1 = "Geek";//It is necessary the parameters should initialize before it pass to ref.

            SetValue1(ref str1);

            Console.WriteLine(str1);//When ref keyword is used the data may pass in bi-directional.

 

            //SetValue1(ref string refObj);//Error you cannot declare while passing ref parameter

 

            //The out is a keyword in C# which is used for the passing the arguments to methods as a reference type.

            string str2 = "Geek";

            SetValue2(out str2);

            //SetValue2(out string str2);//No Error//Comment above two lines to debug the code

            Console.WriteLine(str2);//When out keyword is used the data only passed in unidirectional.

           

            string str3 = "Geek3";

            string str4 = "Geek4";

            SetValue3(ref str3, ref str4);//reference can be used for passing multiple parameters

            Console.WriteLine(str3 + " " + str4);//When ref keyword is used the data may pass in bi-directional.

 

            string str5 = "Geek5";

            string str6 = "Geek6";

            SetValue4(out str5, out str6);//When out keyword is used the data only passed in unidirectional.

            Console.WriteLine(str5 + " " + str6);

        }

 

        static void SetValue1(ref string str1)

        {           

            if (str1 == "Geek")//It is not necessary to initialize the value of a parameter before returning to the calling method.

            {

                Console.WriteLine("Hello!!" + str1);

            }

            str1 = "GeeksforGeeks";

        }

 

        static void SetValue2(out string str1)

        {

            str1 = "";//It is necessary to initialize the value of a parameter before returning to the calling method.

            if (str1 == "Geek")//if you comment above line it will throw error

            {

                Console.WriteLine("Hello!!Geek");

            }

            str1 = "GeeksforGeeks";

        }

 

        static void SetValue3(ref string str3, ref string str4)

        {           

            if (str3 == "Geek3")

            {

                Console.WriteLine("Hello!!" + str3);

            }

            if (str4 == "Geek4")

            {

                Console.WriteLine("Hello!!" + str4);

            }

            str3 = "GeeksforGeeks3";

            str4 = "GeeksforGeeks4";

        }

        static void SetValue4(out string str5, out string str6)

        {

            str5 = "";//It is necessary to initialize the value of a parameter before returning to the calling method.

            str6 = "";

 

            str5 = "GeeksforGeeks5";

            str6 = "GeeksforGeeks6";

        }

 

    }

No comments:

Post a Comment