Arithmetic Expressions
Similar to C++ or Java.
Data Conversions
In C#, data conversions can occur in three ways:
Assignment conversion
occurs automatically when a value of one type is assigned to a
variable of another
only widening conversions can happen via assignment
Example: aFloatVar = anIntVar
Arithmetic promotion
happens automatically when operators in expressions convert their
operands
Example: aFloatVar / anIntVar
Casting
Casting
Casting is the most powerful, and dangerous, technique for conversion
Both widening and narrowing conversions can be accomplished by explicitly
casting a value
To cast, the type is put in parentheses in front of the value being converted
For example, if total and count are integers, but we want a floating point result
when dividing them, we can cast total:
result = (float) total / count;
Control Statement
if (studentGrade >= 60)
Console.WriteLine (Passed);
1/20
if ( <test> )
<code executed if <test> is true> ;
else
<code executed if <test> is false> ;
While Statement
int product;
product = 2;
while (product <= 1000)
{
product = 2 * product;
}
For loop
'For' loops tend to be used when one needs to maintain an iterator value. Usually, as in the
following example, the first statement initialises the iterator, the condition evaluates it against
an end value, and the second statement changes the iterator value.
for (int a =0; a<5; a++)
{
System.Console.WriteLine(a);
2/20
The main drawback of 'foreach' loops is that each value extracted (held in the given example
by the variable 'b') is read-only.
Switch statement
switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case ...
default :
statement-list
}
Classes
C# Framework Class Library (FCL) defines many classes, e.g.,
Console
MessageBox
Int32
Math
The definition of a class includes both methods and data properties:
methods, e.g.,
Console.Write( )
Console.WriteLine( )
Int32.Parse( )
properties, e.g.,
Int32.MinValue
Int32.MaxValue
Math.PI
Math.E
Methods
A method should provide a well-defined, easy-to-understand functionality
A method takes input (parameters), performs some actions, and
(sometime) returns a value
Example: invoking the WriteLine method of the Console class:
3/20
class
dot
User-defined Classes
We can define classes and objects using
a language approach or
a conceptual approach
The language approach deals with syntax .The conceptual approach deals with purpose if
classes and objects
Conceptual Definition
Abstraction
o Abstraction is a concept which facilitates to extract out the essential
information of an object.
o In OOP ( Object Oriented Programming ) , Abstraction facilitates the
easy conceptualization of real world objects into the software program.
o Abstraction lies everywhere! What ever you see, do and live are all
full of abstraction.
o In mathematics, multiplication is a kind of abstraction. The symbol x
is an abstract symbol that can do multiplication of any two elements.
Encapsulation
o Encapsulation is a way of organising data and methods into a structure
by concealing the way the object is implemented, i.e. preventing
access to data by any means other than those specified.
o Encapsulation guarantees the integrity of the data contained in the
object.
4/20
Information Hiding
o purpose of hiding is to make inaccessible certain details that should
not affect other parts of a system.
Hierarchy
o the mapped relationships of sub- and super classes is known as a
hierarchy
Language Definition
Class
o A class is a blueprint or prototype from which objects are created.
Object
o An object is a software bundle of related state and behavior.
o Software objects are often used to model the real-world objects that
you find in everyday life.
o Class: a concept, e.g., the dog concept
o Object - An instance of a concept, e.g., the dog at my home
Inheritance
o Inheritance provides a powerful and natural mechanism for organizing
and structuring your software
o classes inherit state and behavior from their super classes
Interface
o An interface is a contract between a class and the outside world. When
a class implements an interface, it promises to provide the behavior
published by that in interface.
Namespace
o A namespace is for organizing classes and interfaces in a logical
manner.
Placing your code into Namespace makes large software projects easier to
manage.
5/20
6/20
" +
Console.WriteLine();
Console.WriteLine("office has:\n " +
office.floors + " floors\n " +
office.occupants + " occupants\n
office.area + " total area");
office.areaPerPerson();
" +
}
}
Class Construction
7/20
class ConsDemo {
public static void Main() {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
Console.WriteLine(t1.x + " " + t2.x);
}
}
Example #2-A parameterized constructor.
using System;
class MyClass {
public int x;
public MyClass(int i) {
x = i;
}
}
class ParmConsDemo {
public static void Main() {
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
Console.WriteLine(t1.x + " " + t2.x);
}
}
Calling a Method
Each time a method is called, the actual arguments in the invocation are
copied into the formal arguments
int
8/20
Random myRandom;
myRandom = new Random();
To call a method on an object, we use the variable (not the class), e.g.,
Random generator1 = new Random();
int num = generate1.Next();
Destructor
In C# we usually do not use destructor. So who has the control over the
destructor (in C#)? it's the .Net frameworks Garbage Collector (GC).
It is possible to define a method that will be called prior to an objects final
destruction by garbage collector. This method is called destructor.
9/20
}
}
class DestructDemo {
public static void Main() {
int count;
Destruct ob = new Destruct(0);
/* Now, generate a large number of objects. At
some point, garbage collection will occur.
Note: you might need to increase the number
of objects generated in order to force
garbage collection. */
for(count=1; count < 100000; count++)
ob.generator(count);
Console.WriteLine("Done");
}
}
Method Overloading
Method overloading is the process of using the same method name for
multiple methods
Usually perform the same task on different data types
The following lines use the WriteLine method for different data types:
Console.WriteLine ("The total is:");
double total = 0;
Console.WriteLine (total);
Parameter Passing
If a modification on the formal argument has no effect on the actual argument,
it is call by value
If a modification on the formal argument can change the actual argument,
it is call by reference
10/20
Example: ref
Before calling the function ref parameter must be initialized e.g., x=8. If x is not
initialized then you can not call Foo.
11/20
Example: out
Out parameter does not need to initialized before calling. They get the values after
the call.
Example #1
// Swap two values.
using System;
class Swap {
// This method now changes its arguments.
public void swap(ref int a, ref int b) {
int t;
t = a;
a = b;
b = t;
}
}
class SwapDemo {
public static void Main() {
Swap ob = new Swap();
int x = 10, y = 20;
Console.WriteLine("x and y before call: " + x + " " + y);
ob.swap(ref x, ref y);
12/20
Example #2
// Swap two references.
using System;
class RefSwap {
int a, b;
public RefSwap(int i, int j) {
a = i;
b = j;
}
public void show() {
Console.WriteLine("a: {0}, b: {1}", a, b);
}
// This method changes its arguments.
public void swap(ref RefSwap ob1, ref RefSwap ob2) {
RefSwap t;
t = ob1;
ob1 = ob2;
ob2 = t;
}
}
class RefSwapDemo {
public static void Main() {
RefSwap x = new RefSwap(1, 2);
RefSwap y = new RefSwap(3, 4);
Console.Write("x before call: ");
x.show();
Console.Write("y before call: ");
y.show();
Console.WriteLine();
// exchange the objects to which x and y refer
x.swap(ref x, ref y);
Console.Write("x after call: ");
x.show();
Console.Write("y after call: ");
y.show();
}
}
13/20
Params
Any number of parameters we can pass to a method when params are used.
Exampl #1
// Demonstrate params.
using System;
class Min {
public int minVal(params int[] nums) {
int m;
if(nums.Length == 0) {
Console.WriteLine("Error: no arguments.");
return 0;
}
m = nums[0];
for(int i=1; i < nums.Length; i++)
if(nums[i] < m) m = nums[i];
return m;
}
}
class ParamsDemo {
public static void Main() {
Min ob = new Min();
int min;
int a = 10, b = 20;
// call with two values
min = ob.minVal(a, b);
Console.WriteLine("Minimum is " + min);
// call with 3 values
min = ob.minVal(a, b, -1);
Console.WriteLine("Minimum is " + min);
// can call with an int array, too
int[] args = { 45, 67, 34, 9, 112, 8 };
min = ob.minVal(args);
Console.WriteLine("Minimum is " + min);
}
}
14/20
15/20
Return an Array
Example #1
using System;
class Factor {
/* Return an array containing the factors of num.
On return, numfactors will contain the number of
factors found. */
public int[] findfactors(int num, out int numfactors) {
int[] facts = new int[80]; // size of 80 is arbitrary
int i, j;
// find factors and put them in the facts array
for(i=2, j=0; i < num/2 + 1; i++)
if( (num%i)==0 ) {
facts[j] = i;
j++;
}
numfactors = j;
return facts;
}
}
class FindFactors {
public static void Main() {
Factor f = new Factor();
int numfactors;
int[] factors;
factors = f.findfactors(1000, out numfactors);
Console.WriteLine("Factors for 1000 are: ");
for(int i=0; i < numfactors; i++)
Console.Write(factors[i] + " ");
Console.WriteLine();
}
}
16/20
//
//
17/20
// cs_readonly_keyword.cs
// Readonly fields
using System;
public class ReadOnlyTest
{
class MyClass
{
public int x;
public readonly int y = 25; // Initialize a readonly field
public readonly int z;
public MyClass()
{
z = 24;
}
public MyClass(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
}
public static void Main()
{
MyClass p1= new MyClass(11, 21, 32);
// OK
// OK
18/20
Output
p1: x=11, y=21, z=32
p2: x=55, y=25, z=24
----------------------
// Error
Activities
Problem #1;)
Write a c# class of rectangle which has property height and width and method area();
Hints:)
using System;
class Rect {
public int width;
public int height;
public Rect(int w, int h) {
this.width = w;
this.height = h;
}
public int area() {
return this.width * this.height;
}
}
class UseRect {
public static void Main() {
Rect r1 = new Rect(4, 5);
Rect r2 = new Rect(7, 9);
Console.WriteLine("Area of r1: " + r1.area());
Console.WriteLine("Area of r2: " + r2.area());
}
}
Problem 2:)
Write a program in VS which reads principal and interest and shows the compound
interest on a message box.
Hint:
// Interest.cs
2
// Calculating compound interest, using MessageBox and Pow.
19/20
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
27
28
28
29
30
31
using System;
using System.Windows.Forms;
class Interest
{
static void Main( string[] args )
{
decimal amount, principal = ( decimal ) 1000.00;
double rate = .05;
string output;
output = "Year\tAmount on deposit\n";
for ( int year = 1; year <= 10; year++ )
{
amount = principal *
( decimal ) Math.Pow( 1.0 + rate, year );
output += year + "\t" +
String.Format( "{0:C}", amount ) + "\n";
}
MessageBox.Show( output,
"Compound Interest",
MessageBoxButtons.OK,
MessageBoxIcon.Information );
} // end method Main
} // end class Interest
Problem 3:)
Implement a website which uses HTML controls to record voter information e.g.,
Voter list project where name, age, nationality, district, education etc. could be
entered using this website. Hints: For photo (use your jpeg file), sex {male/female},
district {use list box}, age, education {SSC, HSC, Graduation, Higher Degree etc.)
use check box.
Problem 4:)
Also complete the above using web controls. Add also a calendar control to store
birth date of the voter instead of age.
20/20