How to use ref to pass parameter as a reference not a value in C#

2 Answers

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "c#";
            Console.WriteLine(s);

            SetString2(s);
            Console.WriteLine(s);

            SetString1(ref s);
            Console.WriteLine(s);

        }
        static void SetString1(ref string s)
        {
            s = "java";
        }
        static void SetString2(string s)
        {
            s = "java";
        }
    }
}


/*
run:
    
c#
c#
java

*/

 



answered Feb 18, 2017 by avibootz
edited Feb 18, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 7, b = 3;
            Console.WriteLine("a = {0} b = {1}", a, b);

            swap2(a, b);
            Console.WriteLine("a = {0} b = {1}", a, b);

            swap1(ref a, ref b);
            Console.WriteLine("a = {0} b = {1}", a, b);

        }
        static void swap1(ref int a, ref int b)
        {
            int tmp = a;

            a = b;
            b = tmp;
        }
        static void swap2(int a, int b)
        {
            int tmp = b;

            a = b;
            a = tmp;
        }
    }
}


/*
run:
    
a = 7 b = 3
a = 7 b = 3
a = 3 b = 7

*/

 



answered Feb 18, 2017 by avibootz

Related questions

1 answer 244 views
2 answers 224 views
1 answer 139 views
1 answer 129 views
129 views asked Nov 27, 2020 by avibootz
...