forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMethod Parameters in C#
173 lines (110 loc) · 7.54 KB
/
Method Parameters in C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
Method Parameters in C#
Functions or methods are heart of programming language. While crafting your application you will be requiring defining your custom methods now and then. Understanding methods, its parameters and return types are very important. C# provides some keyword like "out", "ref" or "params" to control your method parameters. These are called parameter modifiers. After getting so many phone calls on the same topic, I decided to write a blog on this.
To justify this I developed a project with some sample codes, if you want to download and experiment with that, ping me at facebook.
Before starting describing program sample, I made a small table to give you an idea about the latest (after C/C++ arena) keywords you can use in your method parameters.
Keyword
Description
If nothing is mentioned
Signifies Pass by Value. Called method receives the exact copy of the data being passed
Keyword: “ref” before data type
Initially assigned by the caller; optionally reassigned by called method. Pass by Reference
Keyword: “out” before data type
This is also pass by reference. As the name indicates, output parameters must be assigned by method being called. Unlike ref, it will throw an error otherwise
Keyword: “params”
Variable number of arguments can be send with this keyword. A word of caution, only a single params modifier can be taken for a method.
Now, let us see one by one. First, let us consider, pass by value.
If Nothing is mentioned
Consider I have the following function. I took a basic console application where Program is the class name and entry point Main is static. All the functions I wrote within the class itself. It is advised that you make the necessary changes when you use these feature for other type of application.
static int Add2Numbers(int FirstValue, int SecondValue)
{
return (FirstValue+SecondValue);
}
At the time of calling the method what we do is mentioned below
int firstNo = 4;
int secondNo = 5;
Console.Write("\n\tAddition Result: {0}", Add2Numbers(firstNo, secondNo));
Console.ReadKey();
That is it. Now, consider if I change the Add2Numbers method to something like following
static int Add2Numbers(int FirstValue, int SecondValue)
{
int AddResult = FirstValue+SecondValue;
FirstValue = 10;
SecondValue = 20;
return (AddResult);
}
Nothing will happen to the variables in main function. This is pass by value. Let's move ahead with other modifier as mentioned in the table.
Using ref method parameter modifier
In some situation you might be requiring to leave the control to the method and do not want a single value to be returned back. Called method will get the control to modify and return back a set of values. See the live example, to clarify your concept
static void SwapValues(ref string FirstValue, ref string SecondValue)
{
FirstValue = "I Love My Country";
SecondValue = " India";
}
Now, if the main method has the following:
string FirstString = "Information", SecondString = "Handler";
Console.Write("\n\n\t Initial Values in FirstString and SecondString room respectively: {0},{1}", FirstString, SecondString);
//Call the method with "ref" parameter modifier
SwapValues(ref FirstString, ref SecondString);
Console.Write("\n\n\t After Calling the Method values in FirstString and SecondString room respectively: {0},{1}", FirstString, SecondString);
Console.ReadKey();
What will happen? It will display "I Love My Country India". This is what is the concept behind Pass by reference.
Using "out" parameter modifier
Methods which take out parameters are bound to assign values within method body. To understand this consider the following method body.
static void Add2Numbers(int FirstValue, int SecondValue, out int AddResult)
{
AddResult=FirstValue + SecondValue;
}
See here compulsorily, the method assigned a value. Notice the syntactical part of it as well. No need to return the value after addition. This is also pass by value.
Now, the question is how main method will access it? Note the following code sample
int firstNo = 4;
int secondNo = 5;
//No need to assign
int addResult;
Add2Numbers(firstNo, secondNo, out addResult);
// Just use the addResult variable
Console.Write("\n\tAddition Result: With out Param {0}", addResult);
Console.ReadKey();
Seems similar to ref modifier. Isn't it? Is there any other special purpose of out modifier? Good questions. Let me discuss a special purpose to give you a comprehensive idea about "out".
One tempting feature of out is that you can return multiple values from a single method. Isn't it tempting? Lets move ahead to see a demonstration. Consider the following method body:
static void MultipleReturnValueTest(out int ANumeric, out string AString, out bool TrueFalseBrother)
{
ANumeric = 999;
AString = "Information Management is all about....";
TrueFalseBrother = true;
}
Now, the code segment which a calling function can have. Consider the following:
int BogusNo; string BogusString; bool BogusTestVariable;
MultipleReturnValueTest(out BogusNo, out BogusString, out BogusTestVariable);
Console.Write("\n\\ntReally Enjoyed out Params....................");
Console.Write("\n\t*********************************************");
Console.Write("\n\n\tInteger With out Param {0}", BogusNo);
Console.Write("\n\n\t String: With out Param {0}", BogusString);
Console.Write("\n\n\t Bool: With out Param {0}", BogusTestVariable);
Console.ReadKey();
Pretty interesting if you used C/C++. I found this most interesting. I expect your views on the comment on this.
Using "params" modifier
This is one of the most important modifier. Feeling excited to inform you that you can pass variable number of parameters in a method. The called method consider the parameter(s) as a single logical one. Do you require this at all? Think, a set of number (number of values are not defined) will be input and the method will return sum of the series. Very exciting. Consider the following function:
static int SumOfSeries(params int[] SetOfValues)
{
Console.Write("\n\n\tNumber of Params passed by User:{0}",SetOfValues.Length);
int Sum=0;
if (SetOfValues.Length == 0)
{
return Sum;
}
else
{
for (int k = 0; k < SetOfValues.Length; k++)
Sum += SetOfValues[k];
}
return Sum;
}
See, the syntactical part of it as well. Now, how can I call from main or other functions? Well, follow the following code fragment:
//First way of calling the function
int sumofSeries = SumOfSeries(2, 2, 3, 4, 5,6);
Console.Write("\n\n\tSum of the Series Specified: {0}", sumofSeries);
Console.ReadKey();
//Pretty Interesting? Is there anything else? .
int[] MyValueSet = { 1, 2, 3, 4, 5 };
Console.Write("\n\n\tSum of the Array Specified: {0}", SumOfSeries(MyValueSet));
Console.ReadKey();