재우니의 블로그



In one of our recent post, we discussed about – What is the difference between Ref and Out Keyword in C#?  We have seen both the out and ref are used to returning values and both passes variables by reference only. Out parameter is required to be modified by the method. On the other hand,’s ref allows to modify the original values, which is always may not like to be the case. Like, we want to pass the value as references, but we want this should not be modified in side the method. C# 7.2 introduced a new parameter passing mode called in parameter.


In parameter are like ref parameter only, except they are read-only inside the method.  You can only refer them, they can’t be modified further.

in 지시자를 넣으면 readonly 파라미터가 되어 어떤것도 조작이 불가능하도록 합니다.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
static void Main(string[] args)
{
 
    int num = 20;
    Console.WriteLine(num);
    MyMethodIn(num);
    num++;
    Console.WriteLine(num);
}
 
public static void MyMethodIn(in int x)
{
    int y = x++; //에러
    Console.WriteLine(y);
    y++;
    Console.WriteLine(y);
    Console.WriteLine(x);
}

In the above example, we passed variable num as in parameter, the value is used by the MyMethodIn() but it does not have any modification and used as readonly.

In case you tried to modify the in parameter, you will get an error – Cannot assign to variable “in int” because it is a read-only variable.

1
2
3
4
public static void MyMethodIn(in int x)
     {
         int y = x++;
     }

Cannot assign to variable “in int” because it is a read-only variable.

Cannot assign to variable “in int” because it is a read-only variable.

To summarize, In parameter is useful when you want to pass variables as a reference but you don’t want it to be modified further by the method. Ref parameter does allow this modification, and out parameter is required to be modified.