Monday, January 8, 2018

C# 7.2 : in Parameters

With C# 7.2, a nice set of syntax improvements that enable working with value types were introduced. My favorite among these is in Parameters.

In this post let’s see what in parameters really is.

As you have already know C# had ref and out for a quite a while now. If we recall what ref and out does (within parameter modifier context), it’s basically as follows.
static void Main(string[] args)
{
    Method1(out int i);
    Console.WriteLine(i); // 10
 
    Method2(ref i);
    Console.WriteLine(i); // 20
}
 
static void Method1(out int i)
{
    // Variable i needs to be assigned a value before leaving the method
    i = 10;
}
 
static void Method2(ref int i)
{
    // Variable i might/might not be assigned a value before leaving the method
    i = 20;
}
Both were used to pass the parameter by reference. The difference is when using out parameter, variable needs to be assigned a value before returning from the method. In ref parameter, there is no such requirement, within the method being called you can or not assign a value to ref parameter. But since there is a possibility of a value not being set there, before passing the ref parameter, it should have a value assigned.

But here from the caller, there is no option to say, within the method being called, the parameter should stay as readonly (if we make the parameter readonly, it’s affecting for outside use of the variable as well).

For this comes the in parameters.
static void Main(string[] args)
{
    Method1(out int i);
    Console.WriteLine(i); // 10
 
    Method2(ref i);
    Console.WriteLine(i); // 20
 
    Method3(i);
    Console.WriteLine(i); // 20
}
 
static void Method1(out int i)
{
    // Variable i needs to be assigned a value before leaving the method
    i = 10;
}
 
static void Method2(ref int i)
{
    // Variable i might/might not be assigned a value before leaving the method
    i = 20;
}
 
static void Method3(in int i)
{
    // Variable i is 20 and cannot assign a value
}
You can see, we have Method3 which accepts int i with in modifier. Unlike out and ref, when we are calling the methods which has in parameters, we don’t have to call like Method(in i). We can omit the in modifier, because the variable is going to be readonly within the method being called. Trying to set a value for in parameters from the method being called is illegal.

Isn’t it nice!

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment