Methods
In this chapter you will learn:
Adding methods to a class
Fields are the data of a type(class) while the methods define the behaviours. A method contains a series of statement.
A method can also get input from outside by declaring parameters and output to outside by returning value.
The void return type indicates that no value will return from the method.
A method's signature is its name and parameters' type. And the signature must be unique within its type(class).
A method can have the following modifiers:
- static
- public
- internal
- private
- protected
- new
- virtual
- abstract
- override
- sealed
- unsafe
- extern
Demo method
The following code adds a method to class Rectangle. It calculates the area of the rectangle.
using System;/*from j av a 2 s.com*/
class Rectangle{
public int Width;
public int Height;
public int GetArea(){
return Width * Height;
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Width = 5;
r.Height = 6;
Console.WriteLine(r.GetArea());
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class