0% found this document useful (0 votes)
59 views33 pages

COOPPractic

Uploaded by

antony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views33 pages

COOPPractic

Uploaded by

antony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/342411430

C# OOP Practice

Presentation · June 2020

CITATIONS READS

0 2,002

1 author:

Renas Rajab Asaad


Independent Researcher
49 PUBLICATIONS 321 CITATIONS

SEE PROFILE

All content following this page was uploaded by Renas Rajab Asaad on 24 June 2020.

The user has requested enhancement of the downloaded file.


Renas R. Rekany

Introduction to C-Sharp

C# (pronounced " C sharp") is a simple, modern, object-oriented, and type-safe


programming language. It will immediately be familiar to C and C++
programmers. C# combines the high productivity of Rapid Application
Development (RAD) languages and the raw power of C++.
Visual C# .NET is Microsoft's C# development tool. It includes an interactive
development environment, visual designers for building Windows and Web
applications, a compiler, and a debugger. Visual C# .NET is part of a suite of
products, called Visual Studio .NET, that also includes Visual Basic .NET,
Visual C++ .NET, and the JScript scripting language. All of these languages
provide access to the Microsoft .NET Framework, which includes a common
execution engine and a rich class library. The .NET Framework defines a
"Common Language Specification" (CLS), a sort of lingua franca that ensures
seamless interoperability between CLS-compliant languages and class libraries.
For C# developers, this means that even though C# is a new language, it has
complete access to the same rich class libraries that are used by seasoned tools
such as Visual Basic .NET and Visual C++ .NET. C# itself does not include a
class library.

2. Declaration in C#
Example:
Data Type Range

byte 0 .. 255

sbyte -128 .. 127

short -32,768 .. 32,767

ushort 0 .. 65,535

int -2,147,483,648 .. 2,147,483,647

uint 0 .. 4,294,967,295

long -9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807

ulong 0 .. 18,446,744,073,709,551,615

float -3.402823e38 .. 3.402823e38

1|Page
Renas R. Rekany

double -1.79769313486232e308 .. 1.79769313486232e308

decimal -79228162514264337593543950335 +79228162514264337593543950335

char A Unicode character.

string A string of Unicode characters.

bool True or False.

object An object.

int i, j, k; // as integer
char c, ch; // as character
float f, salary; // as floating
double d; // as double

3. Operators in C#
Example:
Operator Purpose

*, /, % Multiplication, Division, Modulus

+, - Addition , Subtraction

& Logical AND

^ Logical XOR

| Logical OR

v ++ Increment variable v by 1.

v += n Increment variable v by n.

v *= n Multiply variable v by n.

v -= n Subtract n from variable v

== Checks for equality.

2|Page
Renas R. Rekany

!= Checks for inequality.

> Greater than.

< Less than.

>= Greater than or equal to.

<= Less than or equal to.

&& Conditional AND.

|| Conditional OR.

! Conditional NOT

int x = 1;
int y = x + 10 * 100; // multiplication first y = 1001
int z = (x + 10) * 100; // addition first z = 1100
int x = 0;
int y = x++; // x is 1, y is 0
int x = int.Parse(System.Console.ReadLine());

if (x > 100)
{
System.Console.WriteLine("X is greater than 100");
}

4. If and switch statements in C#


Example:
The if-statement method required an additional 1 nanosecond per method invocation. The switch
implementation was faster. If you look at the intermediate code here, you will see that the switch
uses a jump table opcode.
And:The if-statement is implemented with conditional branches. The jump table is faster—it
requires fewer steps for certain inputs.
if (condition)
{
then-statement;
}
else
{
else-statement;
}
// Next statement in the program.

3|Page
Renas R. Rekany

---
switch (caseSwitch)
{
case 1:
Messagebox.Show("Case 1");
break;
case 2:
Messagebox.Show("Case 2");
break;
default:
Messagebox.Show("Default case");
break;
}

5. Loop statements in C#
Example:
Looping statements repeat a specified block of code until a given condition is met.

for (int i = 0; i<=9; i++)


{
Textbox1.text= textbox1.text + i;
}

C# introduces a new loop type called the foreach loop, which is similar to Visual Basic's For
Each. The foreach loop enables iterating through each item in a container class, such as an array.

string[] arr= new string[] {"Jan", "Feb", "Mar"};


foreach (string s in arr)
{
Textbox1.text= textbox1.text + s;
}
The syntax and operation of while and do...while statements are the same in both languages:
while (condition)
{
// statements
}

do
{
// statements
}
while(condition); // Don't forget the trailing ; in do...while loops

4|Page
Renas R. Rekany

6. Break Continue statements in C#


Example:
Eg. Break Statement Eg. Continue Statement

for( int i=0; i<=5; i++) for( int i=0; i<=5; i++)
{ {
if ( i==4) if ( i==4)
{ {
break; continue;
} }
textbox1.text+="The number is"+i; textbox1.text+="The number is"+i;
Output Output

The number is 0; The number is 0;


The number is 1; The number is 1;
The number is 2; The number is 2;
The number is 3; The number is 3;
The number is 5;

7. String functions in C#
Example:

String Functions Definitions

Clone() Make clone of string.

Compare two strings and returns integer value as output. It returns


CompareTo() 0 for true and 1 for false.

The C# Contains method checks whether specified character or


Contains() string is exists or not in the string value.

This EndsWith Method checks whether specified character is the


EndsWith() last character of string or not.

The Equals Method in C# compares two string and returns


Equals() Boolean value as output.

GetHashCode() This method returns HashValue of specified string.

GetType() It returns the System.Type of current instance.

GetTypeCode() It returns the Stystem.TypeCode for class System.String.

5|Page
Renas R. Rekany

Returns the index position of first occurrence of specified


IndexOf() character.

Converts String into lower case based on rules of the current


ToLower() culture.

Converts String into Upper case based on rules of the current


ToUpper() culture.

Insert() Insert the string or character in the string at the specified position.

This method checks whether this string is in Unicode


IsNormalized() normalization form C.

Returns the index position of last occurrence of specified


LastIndexOf() character.

Length It is a string property that returns length of string.

This method deletes all the characters from beginning to specified


Remove() index position.

Replace() This method replaces the character.

Split() This method splits the string based on specified value.

It checks whether the first character of string is same as specified


StartsWith() character.

Substring() This method returns substring.

ToCharArray() Converts string into char array.

Trim() It removes extra whitespaces from beginning and ending of string.

String s=" Hello ";


Textbox1.text= s.Clone();

6|Page
Renas R. Rekany

8. Method types in C#
Example: 1-Build in:
Built in: the methods that the language provides. Such as Math class provide the following
methods:
Abs (x), exp (x), tan (x)
Cos (x), pow (x,y), log (x)
Sin (x), max (x,y), Sqrt (x)
Log10, max, min, round, sqrt.
Example:
Math.abs(x);

2-User defines: the methods that the user defines and call.
Example:
int sum (int x , int y)
{int s=x+y;
Return (s);}

9. Method calling techniques, Overloading in C#


Example:
When you define a method, you basically declare the elements of its structure. The syntax for
defining a method in C# is as follows:
< Access Specifier> < Return Type> < Method Name> (Parameter list) { Body }
Example:
public void add()
{
Body
}
Method overload:
A. C# enable several methods of same name to be defined in same class as long as
these method have different sets of parameters (number of parameter , type of
parameter , order of parameter ) this is called method overloaded .

B. Method overloading commonly is used to create several methods with same


name that perform similar tasks, but on different data types.
Ex:
Static int squire (int x)
{
return (x*x);
}
Static double squire (double x) { return (x*x); }

7|Page
Renas R. Rekany

10. 1D array in C#
Example:
You can store multiple variables of the same type in an array data structure. You declare an array
by specifying the type of its elements.
int[] array1 = new int[5];
An array has the following properties:
 An array can be Single-Dimensional, Multidimensional or Jagged.
 The number of dimensions and the length of each dimension are established when the
array instance is created. These values can't be changed during the lifetime of the instance.
 The default values of numeric array elements are set to zero, and reference elements are
set to null.
 A jagged array is an array of arrays, and therefore its elements are reference types and are
initialized to null.
 Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.
 Array elements can be of any type, including an array type.
 Array types are reference types derived from the abstract base type Array. Since this type
implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#.

11. 2D array in C#
Example:
Arrays can have more than one dimension. For example, the following declaration creates a two-
dimensional array of four rows and two columns.
int[,] array = new int[4, 2];
int[, ,] array1 = new int[4, 2, 3];
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" }, { "five", "six" } };
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };
int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error
array5[2, 1] = 25;
int elementValue = array5[2, 1];
int[,] array6 = new int[10, 10];

8|Page
Renas R. Rekany

12. Passing array in C#


Example:
An array can also be passed to method as argument or parameter. A method process the array and
returns output. Passing array as parameter in C# is pretty easy as passing other value as
parameter. Just create a function that accepts array as argument and then process them. The
following demonstration will help you to understand how to pass array as argument in C#
programming.
public void printarray(int[] print)
{
int i;
for (i = 0; i < 5; i++)
{
textBox1.Text = textBox1.Text + print[i];
textBox1.AppendText(Environment.NewLine);
}
}
private void button1_Click(object sender, EventArgs e)
{
int[] num = new int[5] { 2, 4, 6, 8, 10 };
printarray(num);
}

13. Array Properties in C#


Example:
Most common properties of Array class

Example Explanation Properties


int i = arr1.Length; Returns the length of array. Returns integer value. Length
int i = arr1.Rank; Returns total number of items in all the dimension. Rank
Returns integer value.
bool i = Check whether array is fixed size or not. Returns IsFixedSize
arr.IsFixedSize; Boolean value
bool k = Check whether array is ReadOnly or not. Returns IsReadOnly
arr1.IsReadOnly; Boolean value

Most common functions of Array class:

Example Explanation Function


Array.Sort(arr); Sort an array Sort
Array.Clear(arr, 0, 3); Clear an array by removing all the items Clear
arr.GetLength(0); Returns the number of elements GetLength
arr.GetValue(2); Returns the value of specified items GetValue
Array.IndexOf(arr,45); Returns the index position of value IndexOf
Array.Copy(arr1,arr1,3); Copy array elements to another elements Copy

9|Page
Renas R. Rekany

14. File Stream in C#


Example:
Provides a Stream for a file, supporting both synchronous and asynchronous read and write
operations.
The System.IO namespace has various classes that are used for performing numerous operations
with files, such as creating and deleting files, reading from or writing to a file, closing a file etc.

Example:

FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);

Reading, Writing, Appending text to and in by external text file.

15. Global variables in C#


Example:
Public Declaration
The public keyword is an access modifier for types and type members. Public
access is the most permissive access level. There are no restrictions on accessing
public members, as in this example:

class PointTest
{
public int x;
public int y;
}
Public int a=0;

16. External Text File in C#


Example:
Read
using System;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string rt=File.ReadAllText("F:\\a.txt");

10 | P a g e
Renas R. Rekany

textBox1.Text = rt;
}
}}

Write
using System;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string rt = "Welcome to" +Environment.NewLine + "C# Program";
File.WriteAllText("F:\\a.txt", rt);
textBox1.Text = File.ReadAllText("F:\\a.txt");
}} }

Append
using System;
using System.IO;
private void button1_Click(object sender, EventArgs e)
{
string rt = Environment.NewLine+"Second Stage" +Environment.NewLine + "Students";
File.AppendAllText ("F:\\a.txt", rt);
textBox1.Text = File.ReadAllText("F:\\a.txt");
}}}

17. Functions in C#
Example:
A function allows you to encapsulate a piece of code and call it from other parts of your code.
You may very soon run into a situation where you need to repeat a piece of code, from multiple
places, and this is where functions come in. In C#, they are basically declared like this:

<visibility> <return type> <name>(<parameters>)

<function code>

11 | P a g e
Renas R. Rekany

Example:

public void DoStuff()


{
MessageBox.Show("I'm doing something...");
}

To call a function, you simply write its name, an open parenthesis, then parameters, if any, and
then a closing parenthesis, like this:

DoStuff();

18. Listbox and ComboBox in C#


Example:
This example adds the contents of a Windows Forms TextBox control to a ListBox control when
you click button1, and clears the contents when you click button2.

private void button1_Click(object sender, System.EventArgs e)


{
listBox1.Items.Add("Sally");
listBox1.Items.Add("Craig");
}

private void button2_Click(object sender, System.EventArgs e)


{
listBox1.Items.Clear();
}
Example:
private void Form1_Load(object sender, System.EventArgs e)
{
listBox1.Items.Add("One");
listBox1.Items.Add("Two");
listBox1.Items.Add("Three");
}

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)


{
if ((string)listBox1.SelectedItem == "Two")
MessageBox.Show((string)listBox1.SelectedItem);
}

12 | P a g e
Renas R. Rekany

A ComboBox displays a text box combined with a ListBox, which enables the user to select
items from the list or enter a new value .
comboBox1.Items.Add("Sunday");
comboBox1.Items.Add("Monday");
comboBox1.Items.Add("Tuesday");

19. Timer in C#
Example:
Timer regularly invokes code. Every several seconds or minutes, it executes a method. This is
useful for monitoring the health of an important program, as with diagnostics.

Timer.AutoReset:Indicates "whether the Timer should raise the Elapsed event each time the
specified interval elapses."

Timer.Enabled:MSDN: "Whether the Timer should raise the Elapsed event." You must set this
to true if you want your timer to do anything.

Timer.Interval:The number of milliseconds between Elapsed events being raised. Here "the
default is 100 milliseconds."

Timer.Start:This does the same thing as setting Enabled to true. It is unclear why we need this
duplicate method.

Timer.Stop:This does the same thing as setting Enabled to false. See the Timer.Start method
previously shown.

Timer.Elapsed Event:An event that is invoked each time the Interval of the Timer has passed.
You must specify this function in code.

20. Font and Color Dialog in C#


Example:
A FontDialog control is used to select a font from available fonts installed on a system. A typical
Font Dialog looks like Figure 1 where you can see there is a list of fonts, styles, size and other
options. Please note a FontDialog may have different fonts on different system
depending on what fonts are install on a system.
private System.Windows.Forms.FontDialog fontDialog1;
this.fontDialog1 = new System.Windows.Forms.FontDialog();
-
FontDialog fontDlg = new FontDialog();
fontDlg.ShowDialog();

if (fontDlg.ShowDialog() != DialogResult.Cancel)
{

13 | P a g e
Renas R. Rekany

textBox1.Font = fontDlg.Font;
label1.Font = fontDlg.Font;
textBox1.BackColor = fontDlg.Color;
label1.ForeColor = fontDlg.Color;
}

A ColorDialog control is used to select a color from available colors and also define custom
colors. A typical Color Dialog looks like Figure 1 where you can see there is a list of basic solid
colors and there is an option to create custom colors.

private System.Windows.Forms.ColorDialog colorDialog1;


this.colorDialog1 = new System.Windows.Forms.ColorDialog();
-
ColorDialog colorDlg = new ColorDialog();
colorDlg.ShowDialog();

private void ForegroundButton_Click(object sender, EventArgs e)


{
ColorDialog colorDlg = new ColorDialog();
colorDlg.AllowFullOpen = false;
colorDlg.AnyColor = true;
colorDlg.SolidColorOnly = false;
colorDlg.Color = Color.Red;

if (colorDlg.ShowDialog() == DialogResult.OK)
{
textBox1.ForeColor = colorDlg.Color;
listBox1.ForeColor = colorDlg.Color;
button3.ForeColor = colorDlg.Color;
}
}

private void BackgroundButton_Click(object sender, EventArgs e)


{
ColorDialog colorDlg = new ColorDialog();
if (colorDlg.ShowDialog() == DialogResult.OK)
{
textBox1.BackColor = colorDlg.Color;
listBox1.BackColor = colorDlg.Color;
button3.BackColor = colorDlg.Color;
}
}

14 | P a g e
Renas R. Rekany

21. Events in C#
Example:
Events are user actions such as key press, clicks, mouse movements, etc.,
or some occurrence such as system generated notifications. Applications
need to respond to events when they occur. For example, interrupts. Events
are used for inter-process communication.

For Example:
1-Text events.
2-Mouse events.
3-KeyPress.

22. Class (OOP) in C#


Example:
When you define a class, you define a blueprint for a data type. This does not actually define any
data, but it does define what the class name means. That is, what an object of the class consists
of and what operations can be performed on that object. Objects are instances of a class. The
methods and variables that constitute a class are called members of the class.

Defining a Class
A class definition starts with the keyword class followed by the class name; and the class body
enclosed by a pair of curly braces. Following is the general form of a class definition:

using System;
namespace BoxApplication
{
class Box
{
public double length; // Length of a box
public double breadth; // Breadth of a box
public double height; // Height of a box
}
class Boxtester
{

15 | P a g e
Renas R. Rekany

// In button
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
MessageBox.Show("Volume of Box1 : {0}", volume);

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
MessageBox.Show ("Volume of Box2 : {0}", volume);
} }}

Member Functions and Encapsulation


A member function of a class is a function that has its definition or its prototype within the class
definition similar to any other variable. It operates on any object of the class of which it is a
member, and has access to all the members of a class for that object.

Member variables are the attributes of an object (from design perspective) and they are kept
private to implement encapsulation. These variables can only be accessed using the public
member functions.

16 | P a g e
Renas R. Rekany

using System;
namespace BoxApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength( double len )
{
length = len;
}

public void setBreadth( double bre )


{
breadth = bre;
}

public void setHeight( double hei )


{
height = hei;
}
public double getVolume()
{
return length * breadth * height;
}
}
class Boxtester
{
// In button void
{
Box Box1 = new Box(); // Declare Box1 of type Box

17 | P a g e
Renas R. Rekany

Box Box2 = new Box();


double volume;

// Declare Box2 of type Box


// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
MessageBox.Show("Volume of Box1 : {0}" ,volume);

// volume of box 2
volume = Box2.getVolume();
MessageBox.Show("Volume of Box2 : {0}", volume);
} }}

18 | P a g e
Renas R. Rekany

23. Constructors & Destructors in C#


Example:
Constructors in C#
A class constructor is a special member function of a class that is executed whenever we create
new objects of that class.

A constructor has exactly the same name as that of class and it does not have any return type.
Following example explains the concept of constructor:

using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line()
{
MessageBox.Show("Object is being created");
}

public void setLength( double len )


{
length = len;
}

public double getLength()


{
return length;
}

static void Main(string[] args)


{
Line line = new Line();

19 | P a g e
Renas R. Rekany

// set line length


line.setLength(6.0);
MessageBox.Show("Length of line : {0}", line.getLength());
} }}

C# Destructors
A destructor is a special member function of a class that is executed whenever an object of its
class goes out of scope. A destructor has exactly the same name as that of the class with a
prefixed tilde (~) and it can neither return a value nor can it take any parameters.

Destructor can be very useful for releasing memory resources before exiting the program.
Destructors cannot be inherited or overloaded.

using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line() // constructor
{
MessageBox.Show("Object is being created");
}
~Line() //destructor
{
MessageBox.Show("Object is being deleted");
}

public void setLength( double len )


{
length = len;
}

public double getLength()

20 | P a g e
Renas R. Rekany

{
return length;
}

static void Main(string[] args)


{
Line line = new Line();

// set line length


line.setLength(6.0);
MessageBox.Show("Length of line : {0}", line.getLength());
} }}

24. Inheritance in C#
Example:
One of the most important concepts in object-oriented programming is inheritance. Inheritance
allows us to define a class in terms of another class, which makes it easier to create and maintain
an application. This also provides an opportunity to reuse the code functionality and speeds up
implementation time.

When creating a class, instead of writing completely new data members and member functions,
the programmer can designate that the new class should inherit the members of an existing class.
This existing class is called the baseclass, and the new class is referred to as the derived class.

The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal,
dog IS-A mammal hence dog IS-A animal as well, and so on.

<acess-specifier> class <base_class>


{
...
}
class <derived_class> : <base_class>
{

21 | P a g e
Renas R. Rekany

...
}
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}

// Derived class
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}

class RectangleTester
{
// In button
{

22 | P a g e
Renas R. Rekany

Rectangle Rect = new Rectangle();

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


Messageox.Show("Total area: {0}", Rect.getArea());
} }}

Multiple Inheritance in C#
C# does not support multiple inheritance. However, you can use interfaces to implement
multiple inheritance. The following program demonstrates this:

using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}

// Base class PaintCost


public interface PaintCost
{

23 | P a g e
Renas R. Rekany

int getCost(int area);

// Derived class
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;
}
}
class RectangleTester
{
// In Botton
{
Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();

// Print the area of the object.


MessageBox.Show("Total area: {0}", Rect.getArea());
MessageBox.Show("Total paint cost: ${0}" , Rect.getCost(area));
} }}

24 | P a g e
Renas R. Rekany

25. Overloading & Overriding in C#


Example:
Method overloading can be achieved by using following things :

 By changing the number of parameters used.


 By changing the order of parameters.
 By using different data types for the parameters.

public class Methodoveloading

public int add(int a, int b) //two int type Parameters method

return a + b;

public int add(int a, int b,int c) //three int type Parameters with same method same as above

return a + b+c;

public float add(float a, float b,float c,float d) //four float type Parameters with same method
same as above two method

return a + b+c+d;

25 | P a g e
Renas R. Rekany

Method Overriding can be achieved by using following things :

 Method overriding is only possible in derived class not within the same class where the
method is declared.
 Only those methods are overrides in the derived class which is declared in the base class
with the help of virtual keyword or abstract keyword.

public class Account

public virtual int balance()

return 10;

public class Amount:Account

public override int balance()

return 500;

26 | P a g e
Renas R. Rekany

26. Polymorphism in C#
Example:
The word polymorphism means having many forms. In object-oriented programming paradigm,
polymorphism is often expressed as 'one interface, multiple functions'.

Polymorphism can be static or dynamic. In static polymorphism, the response to a function is


determined at the compile time. In dynamic polymorphism, it is decided at run-time.

using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
MessageBox.Show("Printing int: {0}", i );
}

void print(double f)
{
MessageBox.Show("Printing float: {0}" , f);
}
void print(string s)
{ MessageBox.Show("Printing string: {0}", s); }
// In button
{
Printdata p = new Printdata();

// Call print to print integer


p.print(5);

// Call print to print float


p.print(500.263);

27 | P a g e
Renas R. Rekany

// Call print to print string


p.print("Hello C++");
} }}

Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial class implementation of
an interface. Implementation is completed when a derived class inherits from it. Abstract classes
contain abstract methods, which are implemented by the derived class. The derived classes have
more specialized functionality.

Here are the rules about abstract classes:

 You cannot create an instance of an abstract class

 You cannot declare an abstract method outside an abstract class

 When a class is declared sealed, it cannot be inherited, abstract classes cannot be


declared sealed.

The following program demonstrates an abstract class:

using System;
namespace PolymorphismApplication
{
abstract class Shape
{
public abstract int area();
}
class Rectangle: Shape
{
private int length;
private int width;
public Rectangle( int a=0, int b=0)
{
length = a;
width = b;
}

28 | P a g e
Renas R. Rekany

public override int area ()


{
MessageBox.Show("Rectangle class area :");
return (width * length);
}
}

class RectangleTester
{
// In button
{
Rectangle r = new Rectangle(10, 7);
double a = r.area();
MessageBox.Show("Area: {0}",a);
} }}

Dynamic polymorphism is implemented by abstract classes and virtual functions.

The following program demonstrates this:

using System;
namespace PolymorphismApplication
{
class Shape
{
protected int width, height;
public Shape( int a=0, int b=0)
{
width = a;
height = b;
}
public virtual int area()
{
MessageBox.Show ("Parent class area :");

29 | P a g e
Renas R. Rekany

return 0;
}
}
class Rectangle: Shape
{
public Rectangle( int a=0, int b=0): base(a, b)
{
}
public override int area ()
{
MessageBox.Show ("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape
{
public Triangle(int a = 0, int b = 0): base(a, b)
{
}
public override int area()
{
MessageBox.Show ("Triangle class area :");
return (width * height / 2);
}
}
class Caller
{
public void CallArea(Shape sh)
{
int a; a = sh.area();
MessageBox.Show("Area: {0}", a);
} }

30 | P a g e
Renas R. Rekany

class Tester
{
// In button
{ Caller c = new Caller();
Rectangle r = new
Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
c.CallArea(r);
c.CallArea(t); } }
}

31 | P a g e

View publication stats

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy