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.
ref keyword is used when a called method has to update the passed parameter. out keyword is used when a called method has to update multiple parameter passed. ref keyword is used to pass data in bi-directional way.
In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment.
The in keyword is used in the following contexts: generic type parameters in generic interfaces and delegates. As a parameter modifier, which lets you pass an argument to a method by reference rather than by value. foreach statements.
Ref and out keywords in C# are used to pass arguments within a method or function. Both indicate that an argument/parameter is passed by reference. By default parameters are passed to a method by value. By using these keywords (ref and out) we can pass a parameter by reference.
The following clearly explains the purpose :
passes a variable in to a method by reference. Cannot be set inside the method.
From Official DOCS:
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.
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