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;
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With