Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must use "out" instead of ref?

i wrote some code blocks about ref -out declaration. i think that ref is most useful out. Ok. why i need to use out. i can use always ref everytime:

namespace out_ref
{
    class Program
    {
        static void Main(string[] args)
        {
            sinifA sinif = new sinifA();
            int test = 100;
            sinif.MethodA(out test);
            Console.WriteLine(test.ToString());

            sinif.MethodB(ref test);
            Console.WriteLine(test.ToString());
            Console.ReadKey();
        }
    }

    class sinifA
    {

        public void MethodA(out int a)
        {
            a = 200;
        }

        int _b;
        public void MethodB(ref int b)
        {
            _b = b;
            b = 2*b;
        }
    }

}
like image 817
ALEXALEXIYEV Avatar asked Nov 28 '22 19:11

ALEXALEXIYEV


1 Answers

Yes you can use ref every time but they have different purposes. ref is used for when a parameter is both an input and an output. out is used when the parameter is an output only. It can be used to pass an input but it makes it so the user of a function does not need to declare an instance before using the function because you are in effect saying that you will guarantee an instance is created. It is especially useful in the TryXXX pattern when you are getting a value from a collection

like image 119
Craig Suchanec Avatar answered Dec 09 '22 09:12

Craig Suchanec