chapter 2 c# programming€¦ · the code editor, ... including .net framework assemblies and com...
TRANSCRIPT
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 1
CHAPTER – 2
C# PROGRAMMING
1.1 INTRODUCTION TO VISUAL C# 2008 IDE
The Visual C# integrated development environment (IDE) is a collection of development
tools exposed through a common user interface. Some of the tools are shared with other Visual
Studio languages, and some, such as the C# compiler, are unique to Visual C#. The
documentation in this section provides an overview of how to use the most important Visual C#
tools as you work in the IDE in various phases of the development process.
VISUAL C# TOOLS
The following are the most important tools and windows in Visual C#. The windows for
most of these tools can be opened from the View menu.
The Code Editor, for writing source code.
The C# compiler, for converting C# source code into an executable program.
The Visual Studio debugger, for testing your program.
The Toolbox and Designer, for rapid development of user interfaces by using the mouse.
Solution Explorer, for viewing and managing project files and settings.
Project Designer, for configuring compiler options, deployment paths, resources, and
more.
Class View, for navigating through source code according to types, not files.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 2
Properties Window, for configuring properties and events on controls in your user
interface.
Object Browser, for viewing the methods and classes available in dynamic link libraries
including .NET Framework assemblies and COM objects.
Document Explorer, for browsing and searching product documentation on a local
computer and on the Internet.
HOW THE IDE EXPOSES THE TOOLS
You interact with the tools through windows, menus, property pages, and wizards in the
IDE. The following represents the basic IDE:
You can quickly access any open tool windows or files by pressing CTRL + TAB. For more
information, see Navigating and Searching (Visual C#).
EDITOR AND WINDOWS FORM DESIGNER WINDOWS
The large main window is used by the Code Editor, the Windows Forms Designer, or the
Windows Presentation Foundation Designer. You can switch to Code view or Design view by
clicking Code or Designer on the View menu or by using the keyboard shortcuts F7 or SHIFT +
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 3
F7. While in Design view, you can drag controls onto the window from the Toolbox, which you
can make visible by clicking the Toolbox tab on the left margin. For more information about the
Code Editor, see Editing Code (Visual C#). For more information about the Designers,
see Windows Forms Designer and Getting Started with the WPF Designer.
The Properties window in the lower-right is populated only in Design view. It enables
you to set properties and hook up events for user interface controls such as buttons, text boxes,
and so on. When you set this window to Auto Hide, it will collapse into the right margin
whenever you switch to Code View. For more information about the Properties window and the
Designer, see designing a User Interface (Visual C#).
SOLUTION EXPLORER AND PROJECT DESIGNER
The window in the upper-right is Solution Explorer, which shows all the files in your
project in a hierarchical tree view. When you use the Project menu to add new files to your
project, you will see them reflected in Solution Explorer. In addition to files, Solution
Explorer also displays your project settings, and references to external libraries required by your
application.
The Project Designer property pages are accessed by right-clicking the Properties node
in Solution Explorer, and then clicking Open. Use these pages to modify build options, security
requirements, deployment details, and many other project properties. For more information
about Solution Explorer and the Project Designer, see Creating a Project (Visual C#).
Compiler, Debugger, and Error List Windows
The C# compiler has no window because it is not an interactive tool, but you can set
compiler options in the Project Designer. When you click Build on the Build menu, the C#
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 4
compiler is invoked by the IDE. If the build is successful, the status pane displays a Build
Succeeded message. If there were build errors, the Error List window appears below the
editor/designer window with a list of errors. Double-click an error to go to the problem line in
the source code. Press F1 to see Help documentation for the highlighted error.
The debugger has various windows that display values of variables and type information
as your application is running. You can use the Code Editor window while debugging to specify
a line at which to pause execution in the debugger, and to step through code one line at a time.
For more information, see Building and Debugging (Visual C#).
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 5
1.2 BASIC PROGRAMMING USING VISUAL C#
HELLO WORLD – YOUR FIRST PROGRAM (C# PROGRAMMING)
The following procedure creates a C# version of the traditional "Hello World!" program. The
program displays the string Hello World!
TO CREATE AND RUN A CONSOLE APPLICATION
1. Start Visual Studio.
2. On the menu bar, choose File, New, Project.
The New Project dialog box opens.
3. Expand Installed, expand Templates, expand Visual C#, and then choose Console
Application.
4. In the Name box, specify a name for your project, and then choose the OK button.
The new project appears in Solution Explorer.
5. If Program.cs isn't open in the Code Editor, open the shortcut menu
for Program.cs in Solution Explorer, and then choose View Code.
6. Replace the contents of Program.cs with the following code.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 6
C# Program
1. // A Hello World! program in C#.
2. using System;
3. namespace HelloWorld
4. {
5. class Hello
6. {
7. static void Main()
8. {
9. Console.WriteLine("Hello World!");
10.
11. // Keep the console window open in debug mode.
12. Console.WriteLine("Press any key to exit.");
13. Console.ReadKey();
14. }
15. }
16. }
7. Choose the F5 key to run the project. A Command Prompt window appears that contains
the line Hello World!
Next, the important parts of this program are examined.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 7
COMMENTS
The first line contains a comment. The characters // convert the rest of the line to a comment.
// A Hello World! program in C#.
You can also comment out a block of text by enclosing it between the /* and */ characters. This
is shown in the following example.
/* A "Hello World!" program in C#.
This program displays the string "Hello World!" on the screen. */
MAIN METHOD
A C# console application must contain a Main method, in which control starts and ends.
The Main method is where you create objects and execute other methods. The Main method is
a static (C# Reference) method that resides inside a class or a struct. In the previous "Hello
World!" example, it resides in a class named Hello. You can declare the Main method in one of
the following ways:
It can return void.
static void Main()
{
//...
}
It can also return an integer.
static int Main()
{
//...
return 0;
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 8
With either of the return types, it can take arguments.
static void Main(string[] args)
{
//...
}
-or-
static int Main(string[] args)
{
//...
return 0;
}
The parameter of the Main method, args, is a string array that contains the command-line
arguments used to invoke the program. Unlike in C++, the array does not include the name of the
executable (exe) file.
For more information about how to use command-line arguments, see the examples in Main()
and Command-Line Arguments (C# Programming Guide) and How to: Create and Use
Assemblies Using the Command Line (C# and Visual Basic).
The call to ReadKey at the end of the Main method prevents the console window from
closing before you have a chance to read the output when you run your program in debug mode,
by pressing F5.
INPUT AND OUTPUT
C# programs generally use the input/output services provided by the run-time library of
the .NET Framework. The statement System.Console.WriteLine("Hello World!"); uses
the WriteLine method. This is one of the output methods of the Console class in the run-time
library. It displays its string parameter on the standard output stream followed by a new line.
Other Console methods are available for different input and output operations. If you include
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 9
the using System; directive at the beginning of the program, you can directly use
the System classes and methods without fully qualifying them. For example, you can
call Console.WriteLine instead of System.Console.WriteLine:
using System;
Console.WriteLine("Hello World!");
For more information about input/output methods, see System.IO.
COMMAND-LINE COMPILATION AND EXECUTION
You can compile the "Hello World!" program by using the command line instead of the
Visual Studio Integrated Development Environment (IDE).
TO COMPILE AND RUN FROM A COMMAND PROMPT
1. Paste the code from the preceding procedure into any text editor, and then save the file as
a text file. Name the file Hello.cs. C# source code files use the extension.cs.
2. Perform one of the following steps to open a command-prompt window:
o In Windows 8, on the Start screen, search for Developer Command Prompt,
and then tap or choose Developer Command Prompt for VS2012.
A Developer Command Prompt window appears.
o In Windows 7, open the Start menu, expand the folder for the current version of
Visual Studio, open the shortcut menu for Visual Studio Tools, and then
choose Developer Command Prompt for VS2012.
A Developer Command Prompt window appears.
o Enable command-line builds from a standard Command Prompt window.
See How to: Set Environment Variables.
3. In the command-prompt window, navigate to the folder that contains your Hello.cs file.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 10
4. Enter the following command to compile Hello.cs.
csc Hello.cs
If your program has no compilation errors, an executable file that is named Hello.exe is
created.
5. In the command-prompt window, enter the following command to run the program:
Hello
C# BASICS
1. HOW TO WRITE ON SCREEN IN C#.
Console.WriteLine("I have been studying C# for 2 weeks!");
This will appear on screen, and will disappear immediately. So, we are writing another
statement.
Console.WriteLine("I have benn studying C# for 2 weeks!");
Console.ReadLine();
Now it will remain on screen, unless we press Enter key. Here we see that we can write letters,
numbers and special characters (#) on screen.
String: String is name of variable, and it could be anything letters, numbers and special
characters. We can use string for numbers also, but when we need any arithmetical operation, we
use integers, decimals etc. as variables.
2. STRING CONCATENATION:
We can add two strings, called string concatenation. For example, we are adding first
name and second name to get full name.
string a = "John ";
string b = "Smith";
string c = a + b;
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 11
Console.WriteLine(c);
Console.ReadLine();
3. ADDING TWO NUMBERS:
int a=10;
int b=12;
int c=a+b;
Console.WriteLine(c);
Console.ReadLine();
Here, we use integers as variables, because we want to add them (arithmetical operation).
Integers does NOT take fractional (decimal) values. If we want to perform arithmetical operation
of fractional values; we can take double as variables.
double a = 3.4;
double b = 5.2;
double c = a + b;
Console.WriteLine(c);
Console.ReadLine();
4. HOW C# TAKE INPUT
The program will take input from user, and will display it on screen
string name = Console.ReadLine();
Console.WriteLine(name);
Console.ReadLine();
Integer as input:
Input is always in string. So for integer, we need to convert it first.
int number = Convert.ToInt16(Console.ReadLine());
Console.WriteLine(number);
Console.ReadLine();
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 12
Remember: As the input is always in string, so for integers as input we need to convert it first.
5. TAKE TWO INPUTS (INTEGERS) FROM USER AND ADD THEM.
int number1 = Convert.ToInt16(Console.ReadLine());
int number2 = Convert.ToInt16(Console.ReadLine());
int number3 = number1 + number2;
Console.WriteLine(number3);
Console.ReadLine();
6. TAKE TWO INPUTS (STRING) FROM USER, AND ADD THEM.
string firstname = Console.ReadLine();
string lastname = Console.ReadLine();
string fullname = firstname + lastname;
Console.WriteLine(fullname);
Console.ReadLine();
As, input is always in string, so we did not need to convert it.
CONDITIONAL STATEMENTS IN C#:
The if, if / else, if / else if / else Statement
The switch Statement
THE IF STATEMENT:
Syntax:
if (condition)
{statement}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 13
For example,
int a = Convert.ToInt16(Console.ReadLine());
if (a > 10)
{Console.WriteLine("The number is greater than 10");
Console.ReadLine();
THE IF / ELSE STATEMENT:
Syntax:
if (condition)
{statement}
else
{statement}
For example,
int a = Convert.ToInt16(Console.ReadLine());
if (a > 10)
{Console.WriteLine("The number is greater than 10");}
else
{ Console.WriteLine("The number is 10 or less than 10");}
Console.ReadLine();
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 14
THE IF / ELSE IF / ELSE STATEMENT- (ALSO CALLED NESTED IF)
Syntax:
if (condition)
{statement}
else if (condition)
{statement}
else
{statement}
For example,
int a = Convert.ToInt16(Console.ReadLine());
if (a > 10)
{Console.WriteLine("The number is greater than 10");}
else if (a == 10)
{Console.WriteLine("The number is 10");}
else
{ Console.WriteLine("The number is less than 10");}
Console.ReadLine();
NOTE: We write = two times.
THE SWITCH STATEMENT:
Syntax:
switch (integer a)
{
case 1:
statement
break;
case 2:
statement
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 15
break;
default:
statement
break;
}
NOTE: The default in switch statement is equivalent to else in if statement.
For example,
int week = Convert.ToInt16(Console.ReadLine());
switch (week)
{
case 1:
Console.WriteLine("Monday");
break;
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 16
case 7:
Console.WriteLine("Sunday");
break;
default:
Console.WriteLine("NOT KNOWN");
break;
}
Console.ReadLine();
THE FOR LOOP IN C#
Syntax:
for (initial point; ending point; increament)
{
Statement(s)
}
For example, the following program will write counting from 1 to 20.
for (int i = 1; i < 21; i++)
{
Console.WriteLine(i);
}
Console.ReadLine();
Q. Write table of 2 using for loop in C#.
for (int i = 1; i < 11; i++)
{
int tab = 2 * i;
Console.WriteLine(tab);
}
Console.ReadLine();
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 17
Q. Write a program that print even numbers from 1 to 100.
for (int i = 1; i < 101; i++)
{
if (i % 2 == 0)
{
Console.WriteLine(i);
}
}
Console.ReadLine();
Q. Write a program that take input from user, and write table of that number.
Console.WriteLine("Enter a number:");
int num = Convert.ToInt16(Console.ReadLine());
for (int i = 1; i < 11; i++)
{
int tab = i * num;
Console.WriteLine(tab);
}
Console.ReadLine();
Q. Write a program in C sharp, to find the factorial of 5.
int fact = 1;
for (int i = 5; i > 0; i--)
{
fact=fact*i;
}
Console.WriteLine(fact);
Console.ReadLine();
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 18
Q. Write a program that take input from user, and find factorial of that number.
Console.WriteLine("Enter a number:");
int num = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Its factorial is:");
int fact = 1;
for (int i = num; i > 0; i--)
{
fact=fact*i;
}
Console.WriteLine(fact);
Console.ReadLine();
THE WHILE LOOP
Syntax:
while (condition)
{
statement(s)
}
Q. Write a program in C# using while loop, that take a number from user and return cube of that
number. And the program ends when the input is 11.
int num = Convert.ToInt16(Console.ReadLine());
int cube = num * num * num;
while (num != 11)
{
Console.WriteLine(cube);
break;
}
Console.ReadLine();
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 19
Q. Write a program that starts from 0, increase 1 by 1, and end before 10 using while loop in C
Sharp.
int number = 0;
while (number < 10)
{
Console.WriteLine(number);
number = number + 1;
}
Console.ReadLine();
THE DO - WHILE LOOP
Syntax:
do
{
statement(s)
}
while
{
statement(s)
}
Q. Write a program in C Sharp using do - while loop, that take a number, and increase it 2 by 2,
and ends before 30.
int num = Convert.ToInt16(Console.ReadLine());
do
{
Console.WriteLine(num);
num = num + 2;
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 20
while (num < 30);
Console.ReadLine();
ARRAY IN C#
Syntax:
variable type [] variable name = new variable type [length]
Array of type integer with constant values
int[] myarray = new int[3] { 2, 5, 9 };
Console.WriteLine(myarray[0]);
Console.ReadLine();
NOTE: index 0 inside Console.WriteLine statement represents index of array, that is 2.
In the above myarray; index 0 = 2, index 1 = 5, index 2 = 9.
If we replace 0 by 1, the program will show 5, and for 2, the program will show 9.
Array of type string with constant values
string[] name = new string [3] { "Bilal", "Sohail", "Afzal" };
Console.WriteLine(name[0]);
Console.ReadLine();
Q. Write an array in C# of type integer that take 3 numbers as input (the program must close
after taking 3 inputs).
int[] myarray = new int[3];
myarray[0] = Convert.ToInt16(Console.ReadLine());
myarray[1] = Convert.ToInt16(Console.ReadLine());
myarray[2] = Convert.ToInt16(Console.ReadLine());
Console.WriteLine(myarray);
Console.ReadLine();
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 21
Q. Write an array in C Sharp of type string that take 3 strings (names) as input (the program must
ends after taking 3 inputs).
string[] name = new string[3];
name[0] = Console.ReadLine();
name[1] = Console.ReadLine();
name[2] = Console.ReadLine();
Console.WriteLine(name);
Console.ReadLine();
Q. Write an array in C# of type integer that take 10 numbers as input (Use forloop for
simplicity).
int[] myarray = new int[10];
for (int i = 0; i < 10; i++)
{
myarray[i] = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine(myarray);
Console.ReadLine();
Q. Write a program in C Sharp that take 10 inputs from user, and show their sum.
int[] myarray = new int[10];
for (int i = 0; i < 10; i++)
{
myarray[i] = Convert.ToInt16(Console.ReadLine());
}
int a = 0;
for (int j = 0; j < 10; j++)
{
a = a + myarray[j];
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 22
}
Console.WriteLine(a);
Console.ReadLine();
Q. Write a program in C# that take 10 numbers, and show their average (input could be decimal
or fractional value also).
double[] myarray = new double[10];
for (int i = 0; i < 10; i++)
{
myarray[i] = Convert.ToInt16(Console.ReadLine());
}
double a = 0;
double b = 0;
for (int j = 0; j < 10; j++)
{
a = a + myarray[j];
b = a / 10;
}
Console.WriteLine(b);
Console.ReadLine();
METHODS IN C#
In object oriented programming, we work with objects. Objects are the basic building
blocks of a program. An object consists of data and methods. Methods change the state of the
objects created. They are the dynamic part of the objects; data is the static part.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 23
A method is a code block containing a series of statements. Methods must be declared
within a class or a structure. It is a good programming practice that methods do only one specific
task. Methods bring modularity to programs. Proper use of methods brings the following
advantages:
Reducing duplication of code
Decomposing complex problems into simpler pieces
Improving clarity of the code
Reuse of code
Information hiding
Basic characteristics of methods are:
Access level
Return value type
Method name
Method parameters
Parentheses
Block of statements
Access level of methods is controlled with access modifiers. They set the visibility of
methods. They determine who can call the method. Methods may return a value to the caller. In
case our method returns a value, we provide its data type. If not, we use the void keyword to
indicate that our method does not return values. Method parameters are surrounded by
parentheses and separated by commas. Empty parentheses indicate that the method requires no
parameters. The method block is surrounded with { } characters. The block contains one or more
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 24
statements that are executed, when the method is invoked. It is legal to have an empty method
block.
A method signature is a unique identification of a method for the C# compiler. The signature
consists of a method name and the type and kind (value, reference, or output) of each of its
formal parameters. Method signature does not include the return type.
Any legal character can be used in the name of a method. By convention, method names
begin with an uppercase letter. The method names are verbs or verbs followed by adjectives or
nouns. Each subsequent word starts with an uppercase character. The following are typical
names of methods in C#:
Execute
FindId
SetName
GetName
CheckIfValid
TestValidity
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 25
Simple example
We start with a simple example.
using System;
public class Base
{
public void ShowInfo()
{
Console.WriteLine("This is Base class");
}
}
public class SimpleMethod
{
static void Main()
{
Base bs = new Base();
bs.ShowInfo();
}
}
We have a ShowInfo() method that prints the name of its class.
public class Base
{
public void ShowInfo()
{
Console.WriteLine("This is Base class");
}
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 26
Each method must be defined inside a class or a struct. It must have a name. In our case
the name is ShowInfo. The keywords that precede the name of the method are access specifier
and the return type. Parentheses follow the name of the method. They may contain parameters of
the method. Our method does not take any parameters.
static void Main()
{
...
}
This is the Main() method. It is the entry point to each console or GUI application. It
must be declared static. We will see later why. The return type for a Main() method may be void
or int. The access specifier for the Main() method is omitted. In such a case a default one is used,
which is private. It is not recommended to use public access specifier for the Main() method. It is
not supposed to be called by any other methods in the assemblies. It is only the CLR that should
be able to call it when the application starts.
Base bs = new Base();
bs.ShowInfo();
We create an instance of the Base class. We call the ShowInfo() method upon the object.
We say that the method is an instance method, because it needs an instance to be called. The
method is called by specifying the object instance, followed by the member access operator —
the dot, followed by the method name.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 27
METHOD PARAMETERS
A parameter is a value passed to the method. Methods can take one or more parameters.
If methods work with data, we must pass the data to the methods. We do it by specifying them
inside the parentheses. In the method definition, we must provide a name and type for each
parameter.
using System;
public class Addition
{
public int AddTwoValues(int x, int y)
{
return x + y;
}
public int AddThreeValues(int x, int y, int z)
{
return x + y + z;
}
}
public class MethodParameters
{
static void Main()
{
Addition a = new Addition();
int x = a.AddTwoValues(12, 13);
int y = a.AddThreeValues(12, 13, 14);
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 28
Console.WriteLine(x);
Console.WriteLine(y);
}
}
In the above example, we have two methods. One of them takes two parameters, the other
one takes three parameters.
public int AddTwoValues(int x, int y)
{
return x + y;
}
The AddTwoValues() method takes two parameters. These parameters have int type. The
method also returns an integer to the caller. We use the return keyword to return a value from the
method.
public int AddThreeValues(int x, int y, int z)
{
return x + y + z;
}
The AddThreeValues() is similar to the previous method. It takes three parameters.
int x = a.AddTwoValues(12, 13);
We call the AddTwoValues() method of the addition object. It takes two values. These
values are passed to the method. The method returns a value which is assigned to the x variable.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 29
VARIABLE NUMBER OF ARGUMENTS
A method can take variable number of arguments. For this we use the params keyword.
No additional parameters are permitted after the params keyword. Only one params keyword is
permitted in a method declaration.
using System;
public class SumOfValues
{
static void Main()
{
Sum(1, 2, 3);
Sum(1, 2, 3, 4, 5);
}
static void Sum(params int[] list)
{
Console.WriteLine("There are {0} items", list.Length);
int sum = 0;
foreach (int i in list)
{
sum = sum + i;
}
Console.WriteLine("Their sum is {0}", sum);
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 30
}
We create a Sum() method which can take variable number of arguments. The method
will calculate the sum of values passed to the method.
Sum(1, 2, 3);
Sum(1, 2, 3, 4, 5);
We call the Sum() method twice. In one case, it takes 3 arguments, in the second case 5.
We call the same method.
static void Sum(params int[] list)
{
...
}
The Sum() method can take variable number of integer values. All values are added to the
list array.
Console.WriteLine("There are {0} items", list.Length);
We print the length of the list array.
int sum = 0;
foreach (int i in list)
{
sum = sum + i;
}
We compute the sum of the values in the list.
$ ./variableparams.exe
There are 3 items
Their sum is 6
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 31
There are 5 items
Their sum is 15
This is the output of the example.
ANONYMOUS METHODS
Anonymous methods are inline methods that do not have a name. Anonymous methods
reduce the coding overhead by eliminating the need to create a separate method. Without
anonymous methods developers often had to create a class just to call one method.
using System;
using System.Timers;
public class AnonymousMethod
{
static void Main()
{
Timer timer = new Timer();
timer.Elapsed += new ElapsedEventHandler(
delegate(object source, ElapsedEventArgs e)
{
Console.WriteLine("Event triggered at {0}", e.SignalTime);
}
);
timer.Interval = 2000;
timer.Enabled = true;
Console.ReadLine();
}
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 32
We create a timer object and every 2 seconds we call an anonymous method.
Timer timer = new Timer();
A Timer class generates recurring events in an application.
timer.Elapsed += new ElapsedEventHandler(
delegate(object source, ElapsedEventArgs e)
{
Console.WriteLine("Event triggered at {0}", e.SignalTime);
}
);
Here we plug the anonymous method to the Elapsed event. The delegate keyword is used
to denote an anonymous method.
Console.ReadLine();
At this moment, the program waits for an input from the user. The program ends when
we hit the Return key. Otherwise, the program would finish immediately before the events could
be generated.
PASSING ARGUMENTS BY VALUE, BY REFERENCE
C# supports two ways of passing arguments to methods: by value and by reference. The
default passing of arguments is by value. When we pass arguments by value, the method works
only with the copies of the values. This may lead to performance overheads when we work with
large amounts of data.
We use the ref keyword to pass a value by reference. When we pass values by reference,
the method receives a reference to the actual values. The original values are affected when
modified. This way of passing values is more time and space efficient. On the other hand, it is
more error prone.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 33
Which way of passing arguments should we use? It depends on the situation. Say we
have a set of data, for example salaries of employees. If we want to compute some statistics of
the data, we do not need to modify them. We can pass by values. If we work with large amounts
of data and the speed of computation is critical, we pass by reference. If we want to modify the
data, e.g. do some reductions or raises to the salaries, we might pass by reference.
The following example shows how we pass arguments by values.
using System;
public class PassingByValues
{
static int a = 4;
static int b = 7;
static void Main()
{
Console.WriteLine("Outside Swap method");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
Swap(a, b);
Console.WriteLine("Outside Swap method");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
}
static void Swap(int a, int b)
{
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 34
int temp;
temp = a;
a = b;
b = temp;
Console.WriteLine("Inside Swap method");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
}
}
The Swap() method swaps the numbers between the a and b variables. The original
variables are not affected.
static int a = 4;
static int b = 7;
At the beginning, these two variables are initiated. The variables must be declared static,
because they are used from static methods.
Swap(a, b);
We call the Swap() method. The method takes ‘a’ and ‘b’ variables as arguments.
temp = a;
a = b;
b = temp;
Inside the Swap() method, we change the values. Note that the a and b variables are
defined locally. They are valid only inside the Swap() method.
$ ./swapbyval.exe
Outside Swap method
a is 4
b is 7
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 35
Inside Swap method
a is 7
b is 4
Outside Swap method
a is 4
b is 7
The output shows that the original variables were not affected.
The next code example passes values to the method by reference. The original variables
are changed inside the Swap() method. Both the method definition and the method call must use
the ref keyword.
using System;
public class PassingByReference
{
static int a = 4;
static int b = 7;
static void Main()
{
Console.WriteLine("Outside Swap method");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
Swap(ref a, ref b);
Console.WriteLine("Outside Swap method");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 36
static void Swap(ref int a, ref int b)
{
int temp;
temp = a;
a = b;
b = temp;
Console.WriteLine("Inside Swap method");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
}
}
In this example, calling the Swap() method will change the original values.
Swap(ref a, ref b);
We call the method with two arguments. They are preceded by the ref keyword to
indicate that we are passing arguments by reference.
static void Swap(ref int a, ref int b)
{
...
}
Also in the method declaration, we use the ref keyword to inform the compiler that we
accept references to the parameters and not the values.
$ ./swapbyref.exe
Outside Swap method
a is 4
b is 7
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 37
Inside Swap method
a is 7
b is 4
Outside Swap method
a is 7
b is 4
Here we see that the Swap() method really changed the values of the variables.
The out keyword is similar to the ref keyword. The difference is that when using the ref
keyword, the variable must be initialized before it is being passed. With the out keyword, it may
not be initialized. Both the method definition and the method call must use the out keyword.
using System;
public class OutKeyword
{
static void Main()
{
int val;
SetValue(out val);
Console.WriteLine(val);
}
static void SetValue(out int i)
{
i = 12;
}
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 38
An example shows the usage of the out keyword.
int val;
SetValue(out val);
The val variable is declared, but not initialized. We pass the variable to the SetValue()
method.
static void SetValue(out int i)
{
i = 12;
}
Inside the SetValue() method it is assigned a value which is later printed to the console.
METHOD OVERLOADING
Method overloading allows the creation of several methods with the same name which
differ from each other in the type of the input.
What is method overloading good for? The Qt4 library gives a nice example for the
usage. The QPainter class has three methods to draw a rectangle. Their name is drawRect() and
their parameters differ. One takes a reference to a floating point rectangle object, another takes a
reference to an integer rectangle object, and the last one takes four parameters: x, y, width,
height. If the C++ language, which is the language in which Qt is developed, didn't have method
overloading, the creators of the library would have to name the methods like drawRectRectF(),
drawRectRect(), drawRectXYWH(). The solution with method overloading is more elegant.
using System;
public class Sum
{
public int GetSum()
{
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 39
return 0;
}
public int GetSum(int x)
{
return x;
}
public int GetSum(int x, int y)
{
return x + y;
}
}
public class Overloading
{
static void Main()
{
Sum s = new Sum();
Console.WriteLine(s.GetSum());
Console.WriteLine(s.GetSum(20));
Console.WriteLine(s.GetSum(20, 30));
}
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 40
We have three methods called GetSum(). They differ in input parameters.
public int GetSum(int x)
{
return x;
}
This one takes one parameter.
Console.WriteLine(s.GetSum());
Console.WriteLine(s.GetSum(20));
Console.WriteLine(s.GetSum(20, 30));
We call all three methods.
$ ./overloading.exe
0
20
50
And this is what we get when we run the example.
RECURSION
Recursion, in mathematics and computer science, is a way of defining methods in which
the method being defined is applied within its own definition. In other words, a recursive method
calls itself to do its job. Recursion is a widely used approach to solve many programming tasks.
A typical example is the calculation of a factorial.
using System;
public class Recursion
{
static void Main()
{
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 41
Console.WriteLine(Factorial(6));
Console.WriteLine(Factorial(10));
}
static int Factorial(int n)
{
if (n == 0)
{
return 1;
} else
{
return n * Factorial(n-1);
}
}
}
In this code example, we calculate the factorial of two numbers.
return n * Factorial(n-1);
Inside the body of the factorial method, we call the factorial method with a modified argument.
The function calls itself.
$ ./recursion.exe
720
3628800
These are the results.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 42
METHOD SCOPE
A variable declared inside a method has a method scope. The scope of a name is the
region of program text within which it is possible to refer to the entity declared by the name
without the qualification of the name. A variable which is declared inside a method has a method
scope. It is also called a local scope. The variable is valid only in this particular method.
using System;
public class Test
{
int x = 1;
public void exec1()
{
Console.WriteLine(this.x);
Console.WriteLine(x);
}
public void exec2()
{
int z = 5;
Console.WriteLine(x);
Console.WriteLine(z);
}
}
public class MethodScope
{
static void Main()
{
Test ts = new Test();
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 43
ts.exec1();
ts.exec2();
}
}
In the preceding example, we have the x variable defined outside the Show() method. The
variable has a class scope. It is valid everywhere inside the definition of the Test class, e.g.
between its curly brackets.
public void exec1()
{
Console.WriteLine(this.x);
Console.WriteLine(x);
}
The x variable, also called the x field, is an instance variable. And so it is accessible
through the this keyword. It is also valid inside the exec1() method and can be referred by its
bare name. Both statements refer to the same variable.
public void exec2()
{
int z = 5;
Console.WriteLine(x);
Console.WriteLine(z);
}
The x variable can be accessed also in the exec2() method. The z variable is defined in
the exec2() method. It has a method scope. It is valid only in this method.
$ ./methodscope.exe
1
1
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 44
1
5
This is the output of the methodscope.exe program.
A variable defined inside a method has a local/method scope. If a local variable has the
same name as an instance variable, it shadows the instance variable. The class variable is still
accessible inside the method by using the this keyword.
using System;
public class Test
{
int x = 1;
public void exec()
{
int x = 3;
Console.WriteLine(this.x);
Console.WriteLine(x);
}
}
public class Shadowing
{
static void Main()
{
Test ts = new Test();
ts.exec();
}
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 45
In the preceding example, we declare the x variable outside the exec() method and inside
the exec() method. Both variables have the same name, but they are not in conflict because they
live in different scopes.
Console.WriteLine(this.x);
Console.WriteLine(x);
The variables are accessed differently. The x variable defined inside the method, also
called the local variable, is simply accessed by its name. The instance variable can be referred by
using the this keyword.
$ ./shadowing.exe
1
3
This is the output of the shadowing.exe program.
STATIC METHODS
Static methods are called without an instance of the object. To call a static method, we
use the name of the class and the dot operator. Static methods can only work with static member
variables. Static methods are often used to represent data or calculations that do not change in
response to object state. An example is a math library which contains static methods for various
calculations. We use the static keyword to declare a static method. When no static modifier is
present, the method is said to be an instance method. We cannot use the this keyword in static
methods. It can be used in instance methods only.
The Main() method is an entry point to the C# console and GUI application. In C#, the
Main() method is required to be static. Before the application starts, no object is created yet. To
invoke non-static methods, we need to have an object instance. Static methods exist before a
class is instantiated so static is applied to the main entry point.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 46
using System;
public class Basic
{
static int Id = 2321;
public static void ShowInfo()
{
Console.WriteLine("This is Basic class");
Console.WriteLine("The Id is: {0}", Id);
}
}
public class StaticMethod
{
static void Main()
{
Basic.ShowInfo();
}
}
In our code example, we define a static ShowInfo() method.
static int Id = 2321;
A static method can only work with static variables.
public static void ShowInfo()
{
Console.WriteLine("This is Basic class");
Console.WriteLine("The Id is: {0}", Id);
}
This is our static ShowInfo() method. It works with a static Id member.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 47
Basic.ShowInfo();
To invoke a static method, we do not need an object instance. We call the method by
using the name of the class and the dot operator.
$ ./staticmethod.exe
This is Basic class
The Id is: 2321
This is the output of the example.
HIDING METHODS
When a derived class inherits from a base class, it can define methods that are already
present in the base class. We say that we hide the method of the class that we have derived from.
To explicitly inform the compiler about our intention to hide a method, we use the new keyword.
Without this keyword, the compiler issues a warning.
using System;
public class Base
{
public void Info()
{
Console.WriteLine("This is Base class");
}
}
public class Derived : Base
{
public new void Info()
{
base.Info();
Console.WriteLine("This is Derived class");
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 48
}
}
public class HidingMethods
{
static void Main()
{
Derived d = new Derived();
d.Info();
}
}
We have two classes. The Derived and the Base class. The Derived class inherits from
the Base class. Both have a method called Info().
public class Derived : Base
{
...
}
The (:) character is used to inherit from a class.
public new void Info()
{
base.Info();
Console.WriteLine("This is Derived class");
}
This is an implementation of the Info() method in the Derived class. We use the new
keyword to inform the compiler that we are hiding a method from the base class. Note that we
can still reach the original Info() method. With the help of the base keyword, we invoke the
Info() method of the Base class too.
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 49
$ ./hidingmethods.exe
This is Base class
This is Derived class
We have invoked both methods.
OVERRIDING METHODS
Now we will introduce two new keywords: the virtual keyword and the override
keyword. They are both method modifiers. They are used to implement polymorphic behaviour
of objects. The virtual keyword creates a virtual method. Virtual methods can be redefined in
derived classes. Later in the derived class we use the override keyword to redefine the method in
question. If the method in the derived class is preceded with the override keyword, objects of the
derived class will call that method rather than the base class method.
using System;
public class Base
{
public virtual void Info()
{
Console.WriteLine("This is Base class");
}
}
public class Derived : Base
{
public override void Info()
{
Console.WriteLine("This is Derived class");
}
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 50
public class CSharpApp
{
static void Main()
{
Base[] objs = {new Base(), new Derived(), new Base(),
new Base(), new Base(), new Derived() };
foreach (Base obj in objs)
{
obj.Info();
}
}
}
We create an array of the Base and Derived objects. We go through the array and invoke
the Info() method upon all of them.
public virtual void Info()
{
Console.WriteLine("This is Base class");
}
This is the virtual method of the Base class. It is expected to be overridden in the derived classes.
public override void Info()
{
Console.WriteLine("This is Derived class");
}
We override the base Info() method in the Derived class. We use the override keyword.
Base[] objs = {new Base(), new Derived(), new Base(),
new Base(), new Base(), new Derived() };
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 51
Here we create an array of Base and Derived objects. Note that we used the Base type in
our array declaration. This is because a Derived class can be converted to the Base class because
it inherits from it. The opposite is not true. The only way to have both objects in one array is to
use a type which is top most in the inheritance hierarchy for all possible objects.
foreach (Base obj in objs)
{
obj.Info();
}
We traverse the array and call Info() on all objects in the array.
$ ./virtualmethods.exe
This is Base class
This is Derived class
This is Base class
This is Base class
This is Base class
This is Derived class
This is the output.
Now change the override keyword for new keyword. Compile the example again and run it.
$ ./virtualmethods.exe
This is Base class
This is Base class
This is Base class
This is Base class
This is Base class
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 52
This is Base class
This time we have a different output.
SEALED METHODS
A sealed method overrides an inherited virtual method with the same signature. A sealed
method shall also be marked with the override modifier. Use of the sealed modifier prevents a
derived class from further overriding the method. The word further is important. First, a method
must be virtual. It must be later overridden. And at this point, it can be sealed.
using System;
public class A
{
public virtual void F()
{
Console.WriteLine("A.F");
}
public virtual void G()
{
Console.WriteLine("A.G");
}
}
public class B : A
{
public override void F()
{
Console.WriteLine("B.F");
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 53
public sealed override void G()
{
Console.WriteLine("B.G");
}
}
public class C : B
{
public override void F()
{
Console.WriteLine("C.F");
}
/*public override void G()
{
Console.WriteLine("C.G");
}*/
}
public class SealedMethods
{
static void Main()
{
B b = new B();
b.F();
b.G();
C c = new C();
c.F();
c.G();
}
}
INFS 222 OBJECT ORIENTED PROGRAMMING CHAPTER 2 C# PROGRAMMING
DEPARTMENT OF INFORMATION SYSTEMS, UNIVERSITY OF NIZWA, SULTANATE OF OMAN. 54
In the preceding example, we seal the method G() in class B.
public sealed override void G()
{
Console.WriteLine("B.G");
}
The method G() overrides a method with the same name in the ancestor of the B class. It
is also sealed to prevent from further overriding the method.
/*public override void G()
{
Console.WriteLine("C.G");
}*/
These lines are commented because otherwise the code example would not compile. The
Mono compiler would give the following error: sealedmethods.cs(36,26): error CS0239: `C.G()':
cannot override inherited member `B.G()' because it is sealed.
c.G();
This line prints "B.G()" to the console.
$ ./sealedmethods.exe
B.F
B.G
C.F
B.G
This is the output.