Using In Parameter Modifier : C# 7.2

Changes are the only constant thing in the world and that got little faster with C# new releases as we have minor now releases (also referred as point releases) with significant enhancements. New features are getting added and existing features are getting enhanced. In one my earlier posts, I discussed about Ref and Out improvements that took places in C# 7.0. You can go through the link below.

Ref and Out improvements in C# 7.0

Let’s have a quick look on it

Here we can see that if we want to pass the argument by ref then reference of the instance (value type or reference type) is passed and any change the in the argument in the called method reflects in the calling method as well.

Note – If you are curious about the using the ref keyword with reference type object, you can have a look to one of my previous posts by clicking here.

Out parameters, are also like pass by reference except it enforces a rule that calling method pass the variable without initializing while called method must initialize.

Say you have a big struct or any other value type, that you have to pass as an argument. Everytime you will call the method, a new copy will be created and passed to the method. If this has to be done multiple times then it can be a major performance issue.

Also, out keyword  forces to the called method to initialize the variable but we dont have opposite option. And ref keyword allows to pass the paramter via reference and here caller and called method both can modify the variable.

C# 7.2 introduced another keyword In which provides the ability to pass the argument as readonly. It fails at compile time if there is any code which tries to modify in the called method. The variable must be initialized before passing as a parameter.

Lets see an example

There are few restrictions.

  1. In, Out and Ref keywords cannot be used in async methods.
  2. Cannot be used in iterator methods (which has yield statements)
  3. Marking the arguments of main method as In, makes it invalid as entry method.

To summarize, In keyword can be really useful when you are passing a big value type object to method which is called multiple times because instead of creating a new copy in each call, it will be passed by reference.

Cheers,
Brij

Advertisements