Here lets discuss about the various Parameter modifiers that can be used to manage how arguments are passed to methods.
- Default by Value Parameter : If we are not specifying any Parameter Modifier for an argument, by default it is set to Value Parameter. Since we are having Value types, the invoked method will be working on a copy of the original data. This can be better explained with the example as given below
Here you can see that the values are not changed even after the invoked method has changed the values.
- The out modifier :Out modifier is useful in scenarios where we need to return more than one values. Below example supports this scenario.
The invoking method should set the value to the out parameter.
- The ref modifier : The reference parameter modifier is used in scenarios where we need to change the values in the invoked methods. Unlike the out modifier , here we need to initialize the ref parameters before we pass to any method. The below example better explains the same.
- The params modifier : We can use params modifier to pass array of similar types as arguments to a method as a single logical parameter. If we specify the params modifier , we can pass the parameters as comma delimited arguments. Below example better explains the same as given below
- The optional modifier : The optional parameter modifiers are helpful in allowing the caller with the flexibility of passing only required parameters. The below example illustrate the concept
So here we have defined various C# Parameter modifiers.
No comments:
Post a Comment