COOPPractic
COOPPractic
net/publication/342411430
C# OOP Practice
CITATIONS READS
0 2,002
1 author:
SEE PROFILE
All content following this page was uploaded by Renas Rajab Asaad on 24 June 2020.
Introduction to C-Sharp
2. Declaration in C#
Example:
Data Type Range
byte 0 .. 255
ushort 0 .. 65,535
uint 0 .. 4,294,967,295
ulong 0 .. 18,446,744,073,709,551,615
1|Page
Renas R. Rekany
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
+, - Addition , Subtraction
^ Logical XOR
| Logical OR
v ++ Increment variable v by 1.
v += n Increment variable v by n.
v *= n Multiply variable v by n.
2|Page
Renas R. Rekany
|| 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");
}
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.
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.
do
{
// statements
}
while(condition); // Don't forget the trailing ; in do...while loops
4|Page
Renas R. Rekany
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
7. String functions in C#
Example:
5|Page
Renas R. Rekany
Insert() Insert the string or character in the string at the specified position.
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);}
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
9|Page
Renas R. Rekany
Example:
class PointTest
{
public int x;
public int y;
}
Public int a=0;
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:
<function code>
11 | P a g e
Renas R. Rekany
Example:
To call a function, you simply write its name, an open parenthesis, then parameters, if any, and
then a closing parenthesis, like this:
DoStuff();
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.
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.
if (colorDlg.ShowDialog() == DialogResult.OK)
{
textBox1.ForeColor = colorDlg.Color;
listBox1.ForeColor = colorDlg.Color;
button3.ForeColor = 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.
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 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;
}
17 | P a g e
Renas R. Rekany
// 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
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");
}
19 | P a g e
Renas R. Rekany
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");
}
20 | P a g e
Renas R. Rekany
{
return length;
}
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.
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
Rect.setWidth(5);
Rect.setHeight(7);
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;
}
23 | P a g e
Renas R. Rekany
// 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();
24 | P a g e
Renas R. Rekany
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 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.
return 10;
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'.
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();
27 | P a g e
Renas R. Rekany
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.
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
class RectangleTester
{
// In button
{
Rectangle r = new Rectangle(10, 7);
double a = r.area();
MessageBox.Show("Area: {0}",a);
} }}
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