Reputation: 5261
According to c# 7.2
The "in" operator Passes a variable in to a method by reference. Cannot be set inside the method.
and we can write method like this
public static int Add(in int number1, in int number2)
{
return number1 + number2;
}
and call it using
Add(ref myNo,4);
Now my question is that, what is the Big difference between calling that one and this one**(with or without "in" operator)**
public static int Add(int number1, in int number2)
{
return number1 + number2;
}
and Call like
Add(3,4);
This code also does the same the
it could not be set if we want
,so if the only difference between "in" and without "in" is that we cannot set inside method? or not. if no please give me another example.
Upvotes: 8
Views: 219
Reputation: 62498
The following clearly explains the purpose :
passes a variable in to a method by reference. Cannot be set inside the method.
The in modifier on parameters, to specify that an argument is passed by reference but not modified by the called method.
The only difference is that the incoming parameters value cannot be set within the method when parameters are having in
operator while in normal parameters we can set whatever value we want, using in
we restrict from doing that.
For example:
public static int Add(in int number1, in int number2)
{
number1 = 2; // this will give compile time error as we cannot set it.
return number1 + number2;
}
while in normal case we can set whenever we want though in the example it does not makes sense to set but clearly explains the difference:
public static int Add(int number1,int number2)
{
number1 = 2; // this works.
return number1 + number2;
}
So, we can say that the method parameters become immutable technically.
You can read more details about it here.
Upvotes: 7