|
Level: Beginners
Author: Praveen.V.Nair
Date: Friday, November 09, 2007
About the Author: https://mvp.support.microsoft.com/profile/praveen
Contents
-
C# User defined Methods. 1
-
Introduction. 2
-
Datatypes. 2
-
Importance Main() method. 3
-
Example 1 – Main() method. 3
-
Call a method from
another method. 3
-
Example 2 – Call a method
from another method. 3
-
Example 3 – Call a method
from another method – object reference. 4
-
Methods with return
Values. 4
-
Example 4 – Method with
return value. 5
-
Pass parameters by
reference. 5
-
Example 5 – Pass variable
by reference. 5
-
Return more than one
value from a method. 6
-
Example 6 – Method with
multiple return values. 6
-
Example 7 – Method
returns class object. 7
-
Method Overloading. 7
-
Example 8 – Method
Overloading. 8
-
Infinite number of
parameters. 8
-
Example 9 – Pass any
number of parameters to a function. 8
-
At the End!. 9
Introduction
As you know a C# program is made
with one or more classes. These classes contain source code to do some specific
tasks. We write those code usually in small blocks called ‘methods’ or in other
languages you may learn subroutines, sub programs, module or functions.
You may be already aware of built-in
methods like Math.sqrt(),
Math.Abs(), Console.WriteLine()
etc. In this article we will discuss about user defined methods. Means, how to
write a method!. Why we need to write a method?
The most common answer is – to keep a block of code which we need to use
in many places of a program. We will call that block with a specific name and
use it in the required places instead of writing the whole lines again and
again.
In mathematics you may learned
this:
y = f(x) - Here x is the
input of the process and y is the
output of the process and f is the
function of variable x. We can simply
say “y is a function of x”.
In C#, we use the same format for
methods. It is:
<access
modifier> <return datatype> DisplayName(<datatype> myname)
{
<C#
Code>;
}
A typical C# method example will
be:
public
string DisplayName(string myname)
{
string
greetings = "Good Morning " +
myname;
return (greetings
+ "!");
}
Examples of access modifiers are
public, protected, internal, private etc.
Examples of datatypes are int,
string, float, bool etc.
Access modifiers and datatypes
are out of scope of this article so I stop here and continue with methods.
Datatypes
Data types used as <return datatype> as well as <datatype> of the syntax can be
any C# datatype as well as user defined data types. It can be an array or
object. Or even it doesn’t need to return a value.
Type: void
void is used when a method does not return a value. Note that you
cannot pass a void as a parameter in
a method.
Importance Main() method
Main is the mandatory method in every C# program. Whether it is a
windows application or a console application, you cannot execute a program
without a Main() module. We can say Main() is the starting point of a C#
program.
As you know C# is a case
sensitive language and note the capitalized M. I tell you this because we have
lowercase main() in C/C++ languages.
There are certain rules to use
Main().
·
The return types must be int or void.
·
Main() must have a static modifier
There is an optional parameter –
string array which is used to get the command line parameters given. Used like
this:
static void
Main(string[] args)
A
typical Main() method example is:
Example 1 – Main()
method
// Example 1 – Main() method
// Display "Hello World"
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello World");
}
}
Call a method from another method
The next example
shows how to call a method from main (or any other method)
Example 2 – Call a method from another method
// Example 2
// Call a method from another method
using System;
class Program
{
static void DisplayName(string
myname)
{
Console.WriteLine("Name: " + myname);
}
static void Main()
{
DisplayName("Hello
World");
}
}
Here, you may
noticed that I used static in the new method. That is because, you will get an
error if you do not use this.
‘An object reference is required for the nonstatic
field, method, or property 'Program.DisplayName(string)'
You can call only static
methods from another static method. You know Main() is a static method.
Otherwize you have to create an object reference to solve this. Like:
Example 3 – Call a method from another method – object reference
// Example 3
// Call a method from another method - object reference
using System;
class Program
{
void
DisplayName(string myname)
{
Console.WriteLine("Name: " + myname);
}
static void Main()
{
Program
program = new Program();
program.DisplayName("Hello World");
}
}
Methods with return Values
return statement is used to return a value. It is important that
you must return the same datatype as you specified in the method declaration.
Otherwize you will get an error like this:
Cannot implicitly convert type 'string' to 'int'
Also, it is
important that you must return a value if you specified a datatype other than
void in the declaration. The error you can expect is:
‘not all code paths return a value’
Here is an example
of method with return value:
Example 4 – Method with return value
// Example 4
// Method with return value
using System;
class Program
{
private static int Sum(int a, int b)
{
return
(a + b);
}
static void Main()
{
Console.WriteLine("Sum = " + Sum(10, 20));
//
Console.ReadLine();
}
}
Tip: If you test
these scripts under Visual Studio, you may use Console.ReadLine() at the end of all the programs. It will let you
see the output till you press enter key. Otherwize you will see a flash of
command window.
Pass parameters by reference
Suppose you have a
variable i and you want to increment
its value by one. What you do?
i = i + 1; or i++; correct?
In the same way you
can alter the value of a varilable with methods also. You will pass the variables directly to the
methods by the use of reference. ref is the keyword. (Internally it will
pass the physical address location instead and do the process in that address
location instead of temperory valiables used)
Check this example:
Example 5 – Pass
variable by reference
// Example 5
// Pass variable
by reference
using System;
class Program
{
private static void
Increment(ref int
a)
{
a++;
}
static void Main()
{
int xa
= 10;
Increment(ref
xa);
Console.WriteLine("xa = {0}" , xa);
}
}
Return more than one
value from a method
As you see in y = f(x), it can only return one value.
In many languages this is a problem. People use many crooked ways to accomplish
this. Like returning an array, using global variables, by returning class
objects, using ref etc. But in C# there is an easy way to achieve this. It is
called ‘out’. This way we can eliminate all the demerits of using alternate
ways.
The following example shows how
to use:
Example 6 – Method with multiple return values
// Example 6
// Method with
multiple return values
using System;
class Program
{
private static void DoMath(int a, int b, out int sum, out int product, out double sqrt)
{
sum = a + b;
product = a * b;
sqrt
= Math.Sqrt(a);
}
static void Main()
{
int
sum1, product1;
double
sqrt1;
DoMath(10,20, out
sum1, out product1, out
sqrt1);
Console.WriteLine("Sum = {0}\nProduct = {1}\nSquare = {2}"
, sum1,product1,sqrt1);
}
}
Note the usage of out. You have to use it in both
declaration and calling statements.
One of the other useful features
is return class objects instead of ordinary datatypes.
Example 7 – Method returns class object
// Example 7
// Method
returns class object
using System;
class Program
{
class testclass // Inner Class
{
public int a;
public int b;
}
private static testclass
GetTestclassValues(int a, int b)
{
testclass
t = new testclass();
t.a = a;
t.b = b;
return
t;
}
static void Main()
{
testclass
test = GetTestclassValues(20, 50);
Console.WriteLine("testclass.a = {0}\nestclass.b = {1}" ,
test.a, test.b);
}
}
Method Overloading
In Object Oriented Programming
concepts, there is one concept called Polymorphism. This allows values of
different datatypes to be handled using a uniform interface. Polymorphism in C#
is accomplished by the term called Overloading.
Practically saying – they are different methods with same method name. Such ‘a
method’ is called ‘overloaded method’. When such scenario arising? A small
example below:
In one of our earlier example,
Sum() is a method for finding the a+b. You noticed that this takes only integer
values as input and integer values as output. What happens if you try to pass a
double or float value to this method? You will get two errors:
The best overloaded method match for
'Program.Sum(int, int)' has some invalid arguments
Argument '1': cannot convert from 'float' to
'int'
This can be solved by writing a
new method with your parameters of desired datatypes using the same method
name. Like this:
Example 8 – Method Overloading
// Example 8
// Method
Overloading
using System;
class Program
{
private static int Sum(int a, int b)
{
return
(a + b);
}
private static double Sum(double a, double b)
{
return
(a + b);
}
static void Main()
{
Console.WriteLine("Sum = " + Sum(10.5f, 20));
}
}
Infinite number of parameters
Think of a situation where you
want to pass an unknown number of parameters. It may be 2 or 3 or any number.
Here the C# solution is params. This example will help you to reach there
early.
Example 9 – Pass any number of parameters to a
function
// Example 9
// Pass any
number of parameters to a method
using System;
class Program
{
private static string
ShowNames(params string[]
names)
{
string
str = string.Empty;
for (int i = 0; i < names.Length; i++)
{
str += names[i] + "\n";
}
return
str;
}
static void Main()
{
string
names = ShowNames("You","Me","Them","They","We","Us");
Console.WriteLine("Names:\n\n" + names);
}
}
At the End!
Note that this article has not covered all the areas of
topic – methods. At the time of practice one can face issues as well as
inventions. Happy coding.
|