www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons C# Methods Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
In this lesson we are going to explore some facts about C# methods.

ref Keyword
In C#, as in C++, a method can only have one return value. You overcome this in C++ by passing pointers or references as parameters. In C#, with value types, however, this does not work. If you want to pass the value type by reference, you mark the value type parameter with the ref keyword as shown below.

public void foo(int x, ref int y)

Note that you need to use the ref keyword in both the method declaration and the actual call to the method.

someObject.foo(a, ref b);

out Parameters

C# requires definite assignment, which means that the local variables, a, and b must be initialized before foo is called.

int a, b;
b = 0;
someObject.foo(ref a, b); // not allowed a has not been initialized
a = 0;
b =0;
someObject.foo(ref a, b); // now it is OK

This is unnecessarily cumbersome. To address this problem, C# also provides the out keyword, which indicates that you may pass in un-initialized variables and they will be automatically initialized by the compiler.

public void foo(int x, ref int y, out int z)
a = 0;
b = 0;
someObject.foo(ref a, b, out c);
// no need to initialize c

params Keyword

One can pass an arbitrary number of types to a method by declaring a parameter array with the 'params' modifier. Types passed as 'params' are all passed by value. This is elaborated with the help of the following example:

public static void Main(){
double a = 1;
int b = 2;
int c = 3;
int d = totalIgnoreFirst(a, b, c);

public static int totalIgnoreFirst(double a, params int[] intArr){
int sum = 0;
for (int i=0; i < intArr.Length; i++)
sum += intArr[i];
return sum;

Next >>> Lesson No. 17: C# Method Hiding and Overriding

Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.