2 - C# Programming Language
2 - C# Programming Language
Development
2- Introduction to C#
Programming Language
• Same as in C++
– // This is a comment
– /*
This is a
multiline comment
*/
5
Generating XML Documentation
///
/// <summary>
<summary> The
The Hello
Hello class
class prints
prints aa greeting
greeting
///
/// on
on the
the screen
screen
///
/// </summary>
</summary>
class
class XML_Comments
XML_Comments
{{
///
/// <remarks>
<remarks> We
We use
use console-based
console-based I/O.
I/O.
///
/// For
For more
more information
information about
about WriteLine,
WriteLine, see
see
///
/// <seealso
<seealso cref="System.Console.WriteLine"/>
cref="System.Console.WriteLine"/>
///
/// </remarks>
</remarks>
public
public static
static void
void Main(
Main( ))
{{
Console.WriteLine("This
Console.WriteLine("This is is XML
XML Comments");
Comments");
}}
}}
Common Data Types
C# Type Name VB Type Name .Net Type Name
7
Declarations in C#
• Same as in C++ and Java
int x;
string name,s2;
name=“Ali“;
object abc;
object obj = new object();
public string name;
• Literal values
• M (decimal), D (double), F (float), L (long)
• E.g. double x = 1.3D;
8
Statements
• Operators, assignment and initialization
– Same as in C++ and Java
– E.g. x++; x= x +1
++k; k = k +1
x--; x = x -1;
w+=3; w = w + 3;
m*=2; m = m * 2;
• Strings and Escape character
– Same as in C++ and Java \” \n \t \\
• E.g. path = “c:\\myApp\\myfiles”;
9
First C# Program
12
// Now make use of some format tags.
static void FormatNumericalData(){
Console.WriteLine("The value 99999 in various formats:");
Console.WriteLine("c format: {0:c}", 99999);
Console.WriteLine("d9 format: {0:d9}", 99999);
Console.WriteLine("f3 format: {0:f3}", 99999);
Console.WriteLine("n format: {0:n}", 99999);
// Notice that upper- or lowercasing for hex
// determines if letters are upper- or lowercase.
Console.WriteLine("E format: {0:E}", 99999);
Console.WriteLine("e format: {0:e}", 99999);
Console.WriteLine("X format: {0:X}", 99999);
Console.WriteLine("x format: {0:x}", 99999);
}
Members of Numerical
Data Types
Console.WriteLine("=> Data type Functionality:");
Console.WriteLine("Max of int: {0}", int.MaxValue);
Console.WriteLine("Min of int: {0}", int.MinValue);
Console.WriteLine("Max of double: {0}", double.MaxValue);
Console.WriteLine("Min of double: {0}", double.MinValue);
Console.WriteLine("double.Epsilon: {0}", double.Epsilon);
Console.WriteLine("double.PositiveInfinity: {0}", double.PositiveInfinity);
Console.WriteLine("double.NegativeInfinity: {0}", double.NegativeInfinity);
14
Formatting Output
• The $ special character identifies a string literal as an interpolated string.
– When an interpolated string is resolved to a result string, items with interpolation expressions
are replaced by the string representations of the expression results.
string name = “Salem";
int age = 34;
Console.WriteLine($“Your name is {name}.");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
// Expected output is:
//Your name is Salem.
// Salem is 34 years old.
int n = (int)d;
string s = n.ToString();
int n = int.Parse("54321");
double d = double.Parse(snum);
17
Output/output Statements
• Display on Screen
– Console.WriteLine(……);
– Console.Write(……);
18
© 2018 Pearson Education, Ltd. All R
ights Reserved.
Example
using System;
namespace ConsoleApplication1 {
class myProgram {
static void Main(string[] args){
int x, y;
double r;
//Display Message on Screen
Console.WriteLine("Enter First number:");
//Read Input from keyboard
x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter second number:");
y = int.Parse(Console.ReadLine());
r = (double)x / y;
//Display with format
Console.WriteLine( x+ " / " + y +"=" + r.ToString("0.00"));
r = Math.Pow(x, y);
Console.Out.WriteLine(x + " ^ " + y + "=" + r.ToString(“E02"));
}
}
}
20
Predefined Functions
(Math library)
• Math Class is part of .Net Framework
• Examples: double n;
n = Math.Sqrt(81); // n= 9.0
n = Math.Round(42.889) ; // n = 42.0
n = Math.Round(42.889,1) ; // n = 42.9
n = Math.Ceil(42.889) ; // n = 43
n = Math.Floor(42.889) ; // n = 42
n = Math.Round(42.889,1) ; // n = 42.9
n = Math.Abs(-10); // n = 10.0
n = Math.Pow(2,3) ; // n = 8.0
n = Math.PI; // n = 3.14 ….
n = Math.Log(2.712828) //n=1.0
n = Math.Max(3,7) //n=7.0
n = Math.Min(3,7) //n=3.0
21
Exercise
• If/else
• same as in C++ and Java
• Switch
• same as in C++ and Java
24
Nested if…else Statements
if (studentGrade >= 90)
{
Console.WriteLine("A");
}
else if (studentGrade >= 80)
{
Console.WriteLine("B");
}
else if (studentGrade >= 70)
{
Console.WriteLine("C");
}
else if (studentGrade >= 60)
{
Console.WriteLine("D");
}
else
{
Console.WriteLine("F");
}
Example – Nested If
if (a == 1)
Label1.Text = "one";
else if (a >= 2)
Label1.Text = “Two or More";
else
Label1.Text = “Less than One";
26
Exercise
30
Example - using enum
class Program
{
static void Main(string[] args){
// Make an EmpType variable.
EmpType emp = EmpType.Contractor;
switch (emp) //Check employee type
{
case EmpType.Manager:
Console.WriteLine(“Manager");break;
case EmpType.Grunt: Console.WriteLine(“Grunt");
break;
case EmpType.Contractor:
Console.WriteLine(“Contractor");break;
case EmpType.VicePresident: Console.WriteLine(“VP"); break;
default: Console.WriteLine(“Invalid type");
Repetitions
• Same as in Java
– For Loop
– while loop
– do-while
• foreach
32
For Loop
35
while Loop
• Write C# Program that reads 10 numbers and
compute their summation
class Program {
static void Main(string[] args){
int total = 0,num;
int i = 0;
for(i < 5){
Console.WriteLine("Enter number");
num = int.Parse(Console.ReadLine());
total = total + num;
i++;
}
Console.WriteLine($"The sum is {total}");
}
}
Do-while Loop
40
Manipulating Arrays
• Array Declaraction
int[] arr ={5, 7, 9, 10, 3};
42
Exercise
• Read unknown numbers of numbers from the
keyboard (separated by space) and compute their
summation
– Using a string to read all number
string line = Console.ReadLine();
– Split the numbers as separate array of string
char [] sep = { ' ', ','};
string[] snum = line.Split(sep);
– Create an array of integers (or double) with the same size
int[] num = new int[snum.Length];
– Use loop to assign numbers to array
for (int i = 0; i < snum.Length; i++)
num[i] = int.Parse(snum[i]);
Creating a Computed
Size Array
• The array size does not need to be a compile-time
constant
– Any valid integer expression will work
– Array size specified by compile-time integer constant:
long[
long[ ]] row
row == new
new long[4];
long[4];
– Array size specified by run-time integer value:
string
string ss == Console.ReadLine();
Console.ReadLine();
int
int size
size == int.Parse(s);
int.Parse(s);
long[
long[ ]] row
row == new
new long[size];
long[size];
Copying Array Variables
long[
long[ ]] row
row == new
new long[4];
long[4]; 0 0 0 0
long[
long[ ]] copy
copy == row;
row; row
...
...
row[0]++;
row[0]++;
long copy
long value
value == copy[0];
copy[0];
Console.WriteLine(value);
Console.WriteLine(value); Variabl Instan
e ce
Array Properties
long[
long[ ]] row
row == new
new long[4];
long[4]; row.Rank
row.Rank 11
0 0 0 0 row.Length
row.Length 44
row
int[,]
int[,] grid
grid == new
new int[2,3];
int[2,3];
grid.Rank
grid.Rank 22
0 0 0 grid.Length
grid.Length 66
grid 0 0 0
Checking Array Bounds
row
row grid
grid
grid.GetLength(0)==2
grid.GetLength(0)==2
row.GetLength(0)==6
row.GetLength(0)==6
grid.GetLength(1)==4
grid.GetLength(1)==4
row.Length==6
row.Length==6
grid.Length==2*4
grid.Length==2*4
Dynamic Arrays
• C# arrays do not support re-dimensioning.
– This means that once you create an array, you can’t change
its size.
– Instead, you would need to create a new array with the
new size and copy values from the old array to the new,
which would be a tedious process.
• However, if you need a dynamic array-like list, you
can use one of the collection classes provided to
all .NET languages through the .NET class library.
• One of the simplest collection classes that .NET offers
is the ArrayList, which always allows dynamic
resizing.
48
ArrayList
• Using an ArrayList in C#
// Create an ArrayList object. It's a collection, not an array,
// so the syntax is slightly different.
ArrayList dynamicList = new ArrayList();
// Add several strings to the list.
// The ArrayList is not strongly typed, so you can add any data type
// although it's simplest if you store just one type of object
// in any given collection.
dynamicList.Add("one");
dynamicList.Add("two");
dynamicList.Add("three");
// Retrieve the first string. Notice that the object must be converted to a
// string, because there's no way for .NET to be certain what it is.
string item = (string) dynamicList[0];
// OR
string item = Convert.ToString(dynamicList[0]);
49
List Collection
• List Class
– Used to maintain data for a specific type
List<type/class> list1 = new List<type/class>() [{…..}];
//optional
– Example:
List<string> list1 = new List<string>() {"A","B","C"};
List1.Add(“X”);
List1.Remove(“A”);
if(list1.contains(“B”)) ……….;
For(int i=0;i<list1.Count;i++) Console.WriteLine(list1[i]);
Foreach(string x in list1) Console.WriteLine(x);
50
Exercise
• Write a C# program that uses a dynamic list for
friend names.
52
Exercise
• Main is a method
– Use the same syntax for defining your own methods
using
using System;
System;
class
class ExampleClass
ExampleClass
{{
static
static void
void ExampleMethod(
ExampleMethod( ))
{{
Console.WriteLine("Example
Console.WriteLine("Example method");
method");
}}
static
static void
void Main(……
Main(…… ))
{{
//
// ...
...
ExampleMethod(
ExampleMethod( );
);
}}
}}
Static Class Members
55
Example – Defining methods
Using References as Method
Parameters
• References can be used as parameters
– When passed by value, data being referenced may
be changed
77 55 55 77
••
static
static void
void Swap(int
Swap(int x,
x, int
int y)
y)
{{
int
int temp=x;
temp=x; x=y;
x=y; y=temp;
y=temp;
}}
int
int a=5,b=7;
a=5,b=7;
Swap(a,b);
••
Swap(a,b);
Console.WriteLine(“a=“
Console.WriteLine(“a=“ ++ a+”
a+” ,, b="
b=" ++ b);
b);
Passing Parameters By
Reference
• Methods access the parameter values directly.
– If a method changes the value of a pass-by-reference
parameter, the original object is also modified
• Use ref keywords in both function call and definition
• Example
– Function definition
static void swap(ref int x, ref int y)
{ int temp = x; x=y; y=temp; }
– Function call
int a = 7, b = 3;
swap(ref a, ref b); // Function call in the main method
Console.WriteLine(" a = "+ a + " and b= " + b);
58
Output Parameter
59
Optional Parameters
try{
//statements
}
catch (Exception ee) {
//handling exceptions
}
finally {
//clean used memory and close connections
}
66
Example - Exceptions
• Simple Class
68
Example
• Class definition
public class Product{
private string name;
private decimal price;
private string imageURL;
}
• Creating Objects
Product p1 = new Product( );
• Release the object from memory
p1 = null;
69
Class Interactions
• Class can interact with each other using
– Properties: allow to access and/or modify object data
(attributes)
• Similar to set and get methods in C++ classes
70
Adding Class Properties
• Used to set and get the value for a given attribute
• Property name is the same name as the corresponding
attribute with first letter in capital
• Two Accessors (properties can have both or one accessor)
• get accessor is used to the value for an attribute
• set accessor is used to set the value for a given attribute
public class Product public decimal Price {
{ get { return price;}
private string name; set { price= value;}
private decimal price; }
private string imgUrl; public string ImgUrl {
public string Name { get { return imgUrl;}
get { return name;} set {imgUrl = value;}
set { name = value;} }
} 71 }
Using Properties
72
Auto-implemented properties
• In some cases, property get and set accessors just assign a value
to or retrieve a value without including any additional logic.
• An auto-implemented property by using the get and set keywords
without providing any implementation.
• Auto-implemented properties are used to simplify the C# code.
74
Exercise
• Define a class to main employee name and his/her
salary
• Uses a dynamic list for employee information.
• The program should repeatedly display the following
menu and perform the corresponding actions
– Add a new employee
– Remove the ith friend
– Print information about all employees
– Print the salary for a given employee name
– Stop the program
Namespaces
• Namespaces are used to organize different types in
class library.
namespace MyCompany{ namespace MyCompany.MyApp
namespace MyApp{ {
public class Product public class Product
{ {
…………………. ………………….
} }
} }
}
• Using namespaces
using namespace MyComany.MyApp;
Product p = new Product();
• OR MyComany.MyApp.Product p = new MyComany.MyApp.Product();
76
Reading and Writing files
• Import input/output file using
– using System.IO;
77
Example – Writing to
output file
• Writing a message to an output file
try{
StreamWriter r = new
StreamWriter(“message.txt");
r.WriteLine("This is an output
file...........");
r.Close();
}
catch (Exception ee){
Console.WriteLine("Problem in writing to
file");
78
}
Example – Reading from
input file
• Reading two numbers in each line from a text file
int x, y;
string s;
string[] w;
try{
StreamReader fin = new StreamReader(@"C:\....\ConsoleApplication2\TextFile1.txt");
while ((s=fin.ReadLine())!=null){
w=s.Split(' ');
x=int.Parse(w[0]); y=int.Parse(w[1]);
Console.WriteLine(x+" "+y);
}
fin.Close();
}
catch (Exception ee){ //other exceptions e.g. FileNotFoundException
Console.WriteLine(“Problem in reading from file");
}
79
Accessing all folders/files
80
Extracting Server Information
• Environment.CurrentDirectory
• Environment.MachineName
• Environment.UserDomainName
• Environment.UserName
• Environment.OSVersion
• Directory.GetCurrentDirectory( 81
System.Environment Class
static int Main(string[] args) {
// Helper method within the Program class.
ShowEnvironmentDetails();
Console.ReadLine();
return -1;
}
static void ShowEnvironmentDetails() {
// Print drives on this machine, and other interesting details.
foreach (string drive in Environment.GetLogicalDrives())
Console.WriteLine("Drive: {0}", drive);
Console.WriteLine("OS: {0}", Environment.OSVersion);
Console.WriteLine("Number of processors: {0}", Environment.ProcessorCount);
Console.WriteLine(".NET Version: {0}", Environment.Version);
}
82
Accessing all files
83
Exercise – File contents
84
Downloading Web Contents
85
C# Collections and
Generics
Collections
• Two Types of Collections
– System.Collections (non-generic collections)
• to store and interact with bits of data used within an application.
– Generic Collections
• New namespace was introduced in the base class libraries:
System.Collections.Generic.
• Generic containers are often favored over their non-
generics
– typically provide greater type safety and performance
benefits.
Types of System.Collections
System.Collections Meaning in Life
Class
ArrayList Represents a dynamically sized collection of objects listed in
sequential order
BitArray Manages a compact array of bit values, which are represented
as Booleans, where true indicates that the bit is on (1) and
false indicates the bit is off (0)
Hashtable Represents a collection of key-value pairs that are organized
based on the hash code of the key
Queue Represents a standard first-in, first-out (FIFO) collection of
objects
SortedList Represents a collection of key-value pairs that are sorted by
the keys and are accessible by key and by index
Stack A last-in, first-out (LIFO) stack providing push and pop (and
peek) functionality
Generic Collections
• Advantages:
– Provide better performance
• No need for casting: no boxing or unboxing penalties when storing
value types.
– Type safe - can contain only the type of type you specify.
Generic Collections
List1.Add(“X”);
List1.Remove(“A”);
if(list1.contains(“B”)) ……….
91
Example – Define Person Class
class Person
{
public string FirstName {get;set;}
public string LastName { get; set; }
public int Age { get; set; }