C# class method
In this chapter you will learn:
- What is a method in a class
- Syntax to create a method
- Example for a method
- Note for method definition
- Assign value to local variable
Description
A method performs an action in a series of statements.
Syntax
In C#, the definition of a method consists of method modifiers, return value type, method name, input arguments enclosed in parentheses, followed by the method body enclosed in curly braces:
[modifiers] return_type MethodName([parameters])
{
// Method body
}
Each parameter consists of the name of the type of the parameter, and the name by which it can be referenced in the body of the method.
If the method returns a value, a return statement must be used with the return value to indicate each exit point.
Example
The following code shows how to invoke a method.
using System; /*from w w w .j a v a 2 s.c o m*/
class MainClass
{
static void Main()
{
Console.WriteLine("Pi is " + MathTest.GetPi());
int x = MathTest.GetSquareOf(5);
Console.WriteLine("Square of 5 is " + x);
MathTest math = new MathTest();
math.value = 30;
Console.WriteLine("Square of 30 is " + math.GetSquare());
}
}
class MathTest
{
public int value;
public int GetSquare()
{
return value*value;
}
public static int GetSquareOf(int x)
{
return x*x;
}
public static double GetPi()
{
return 3.14159;
}
}
The code above generates the following result.
Note
If the method doesn't return anything, you specify a return type of void because you can't omit the return type altogether.
If it takes no arguments, you still need to include an empty set of parentheses after the method name.
Example 2
C# requires that local variable must have assigned value.
using System;/* w w w.j av a 2s . c o m*/
class Program
{
static void Main(string[] args)
{
int i;
Console.WriteLine(i);
}
}
Compile the code above:
To fix the problem, assign a value to the local variable i.
using System;/*from w w w . j a v a2s . c om*/
class Program
{
static void Main(string[] args)
{
int i = 5;
Console.WriteLine(i);
}
}
We don't need to initialize each elements in an array explicitly, since array elements are initialized by C#.
Next chapter...
What you will learn in the next chapter:
- What is method parameter
- Pass-by-value versus pass-by-reference
- Note for Pass-by-value
- Example for Pass-by-value versus pass-by-reference
- Note for parameter