What are in-parameter modifiers in C#?
The parameter modifiers in, out, and ref are used while passing reference types or value types to methods. They define how the arguments to the parameters will be treated within methods and outside of them.
Explanation
The three modifiers have the following use cases:
ref: Indicates that the parameter can be modified.out: Indicates that the parameter must be modified.in: Indicates that the parameter cannot be modified.
The in-parameter modifier
The in-parameter modifier enables the argument to be passed by reference, but it cannot be altered. This ensures that a new reference to reference types is not allotted.
Important points about the in-parameter modifier
- The user cannot implement an in-parameter modifier with async methods, but their use is allowed with synchronous methods that return a task.
- The user cannot implement an in-parameter modifier with iterator methods that have a
yield returnoryield break. - Method overloading is impossible if the methods only differ by the parameter modifier, as parameter modifiers are not a part of the method signature.
Example
The following example demonstrates how the in modifier causes the arguments to be passed by reference, without allowing alteration.
The program creates an object Person and passes its instance to the ChangeStatus method as a reference using an in-parameter modifier. The example shows that changing the reference of the parameter will throw an error; however, altering the data the reference points to is still possible.
using System;class Educative{public class Person{public string FirstName { get; set; }public string LastName { get; set; }public bool status { get; set; }}static void ChangeStatus(in Person person ){// changing the reference of person will throw an error// person = new Person();// Changing data referred to by person is possibleperson.status = true;}static void Main(){var person = new Person {FirstName = "Sammy", LastName = "Smith", status = false};ChangeStatus(person);Console.WriteLine(person.status);}}
Output
true
Free Resources