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.
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 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.
yield return
or yield break
.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 possible person.status = true; } static void Main() { var person = new Person {FirstName = "Sammy", LastName = "Smith", status = false}; ChangeStatus(person); Console.WriteLine(person.status); } }
true
RELATED TAGS
CONTRIBUTOR
View all Courses