View
219
Download
0
Category
Preview:
Citation preview
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 1/38
C# - In the beginning
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 2/38
The Hello,World! C# Program
//Example2-1.cs
//The first program in C#
Class HelloWorld
{static void Main()
{
System.Console.WriteLine("Hello,World!");
}
}
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 3/38
//Example2-2.cs
//The second program in C#
usingSystem;
Class HelloWorld{
static void Main()
{
Console.WriteLine("Hello,World!");}
}
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 4/38
Using Local Variable
//Example2-3.cs
//Local variables.
Using System;
Class MyClass
{
static void Main()
{
string myString = "Hello,World!";
Console.WriteLine("The string is:"+myString);}
}
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 5/38
The Program Architecture
A C# program may contain one or more files.
Any file can contain any of the following elements:
Directives
Namespaces(which can contain all other elements andnamespaces)
Classes
Structs(structures)
Interfaces
Delegates Enums(enumerations)
Function members(such as methods, properties, indexers,and so forth)
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 6/38
DataTypes
In C#, there are two types
Value types: Variables that stored at a
values on the stack. Reference types: Variables that store
memory addresses of the data stored on
the heap.
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 7/38
Built in Data Types
bool
byte
sbyte char
decimal
double float
int
uint
long
ulong object
short
ushort string
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 8/38
Value Types
Value types include the numeric types
(integers, floats, and so forth) and the Boolean
type (bool).
They also include user-defined types such as
structs and enumerations.
Bool - byte - char decimal double enum
Float int long sbyte - struct - uint
ulong ushort
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 9/38
Variable Initialization
intmyValue=123; intmyValue=0;
intmyValue=newint();
Struct :structPoint
{
intx;
inty;
}
Point myPoint=newPoint();
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 10/38
Reference Types
A reference-type variable does not contain thedata itself;
It actually contains the memory address of the
data.
The following are the C# reference types:
± Class
± Interface
± Delegate
± Object
± String
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 11/38
Boxing and Unboxing
The boxing operation is accomplished by
assigning the value-type variable to a variable
of the type object:
± Int myInt = 123;
± Object myObj = myInt; //boxing
This means moving the value 123 from the
stack to the heap.
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 12/38
Unboxing
In order to convert the variable back to a
value type you use the unboxing operation,
which is performed by casting the reference-
type variable with (int).
The following statement assigns the value
pointed to by myObj to a new value-type
variable, yourInt:
yourInt=(int)myObj; //unboxing
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 13/38
Operators
Arithmetic : + , , * , /
Modulo : %
Compound Assignment : *= x*=y; x=x*y;
/= x/=y; x=x/y;
%= x%=y; x=x%y; += x+=y; x=x+y;
= x=y; x=xy;
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 14/38
Increment and decrement operators are
classified as unary or primary arithmetic
operators.
x++; // increase the value of x by one
y--; // decrease the value of y by one
--y+x //means decrement y before adding its
value to x. (prefix)
y--+x //means decrement y after adding its
value to x. (suffix)
An Example : Increment and Decrement
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 15/38
Formatting Results
Currency
± Console.WriteLine("{0:C}",1.2);
±Output = $1.20
If the number 1.2 is negative, like this:
± Console.WriteLine("{0:C}",-1.2);
± It appears inside parentheses like this: ($1.20).
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 16/38
The Decimal Format
To display a number preceded by a specified
number of zeroes, use the format character
D or d, like this example:
± Console.WriteLine("{0:D5}",123);
The result of this statement is 00123.
The number following the letterD
determines the number of decimal places in
the output.
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 17/38
The Fixed-point Format
To display a number followed by a specified
number of decimal places, use Forf, like
these examples.
The output of each statement is written next
to it as a comment.
± Console.WriteLine("{0:F2}",12);
//12.00 two decimal places
± Console.WriteLine("{0:F0}",12);
//12 no decimal places
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 18/38
The General Format To display a number in the default format, use
the letterGorglike this: ± Console.WriteLine("{0:G}",1.2);//1.2
± Console.WriteLine("{0:G}",1.23);//1.23
As you can see in the comments that followthe statements, this is the same output
produced by no formatting at all.
The statements are then equivalent to thesestatements:
± Console.WriteLine("{0}",1.2);
± Console.WriteLine("{0}",1.23);
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 19/38
There are scientific format and hexadecimal
formats.
Do the following example for formats and youcan understand how C# handles them
Example : Number Formats
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 20/38
The stringType
String myString;
String myString="Welcome to the string
world!"; String myString="My friend, \nWelcome to
the string world!";
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 21/38
String Operators
To concatenate two strings, use the + operator
as in this example:
± String myString="Hello"+","+"World!";
You can also concatenate string variables.
First declare and initialize the variables:
± String hello="Hello";
String world="World!";
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 22/38
Reading the Keyboard Input
To read input from the keyboard, use the .NET
method ReadLine.
Ex : string myString=Console.ReadLine();
Example : Keyboard input
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 23/38
Converting Strings to Numbers
Long myLong = Convert.ToInt64(myString);//convert to long
Float myFloat = Convert.ToSingle(myString);//convert to float
Double myDouble =Convert.ToDouble(myString); //convert to double
Decimal myDecimal =
Convert.ToDecimal(myString); //convert to decimal
Example : Convert Strings
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 24/38
Using the Parse Method
The second way to convert strings to numbers
is by using the Parse method, one of the .NET methods.
It can be used like this:
Int myInt=Int32.Parse(myString); ± Int64.Parse(myString)//converttolong
± Single.Parse(myString)//converttofloat
± Decimal.Parse(myString)//converttodecimal ± Double.Parse(myString)//converttodouble
Example : Convert using Parse
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 25/38
Relational OperatorsOperator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Example : Relational Operators
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 26/38
Logical Operators
Operator Description
&& AND(Short-circuit evaluation)
|| OR(Short-circuit evaluation)
& AND
| OR
! NOT
Short ± cir cuit evaluation : if one expression is
wrong, none of the following expression will be
evaluated.
Ex: (x>5)&&(y==10)//false
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 27/38
The if-else Construct
if(salary>2000)
{
Console.Write("Salary is greater than 2k"); //The original
result}
Else
{
Console.Write("Salary is less than or equal to 2k"); //TheAlternative result
Example : IfElse
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 28/38
The switch Construct
Example : Switch Construct
The Conditional Expression The conditional expression is used to build a
simple conditional statement. condition ? expression_1 : expression_2
condition is the Boolean expression to test.
Which return True or False by evaluatingexpression1 and 2.
Example : ConditionalExpression
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 29/38
Using Libraries DLL
//Example4-5a.cs//Compile as DLL.
Public class Class1
{public static long Factorial(long i)
{
return((i<=1)?1:(i* Factorial(i-1)));}
}
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 30/38
Use the DLL//Example4-5b.cs
Using System;Public class MyClass
{
static void Main()
{Console.Write("Please enter an integer:");
longn=Convert.ToInt64(Console.ReadLine());
Console.WriteLine(Class1.Factorial(n)); //calling the method
}
}
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 31/38
A First Look at the C# Code//EmployeeDLL.cs a class file
Public class Employee
{
//Fields:
public string name;
public string id;
//Methods:
public double CalculateSalary(int hoursWorked,double rate)
{
double salary;
salary=rate* hoursWorked;
return salary;
}
}
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 32/38
Lets use this class file
//MyProgram.cs
usingSystem;
Class MyClass
{
static void Main()
{Employee emp=new Employee();
emp.name=JohnMartinSmith;
emp.id=ABC123";
double weeklyPayment=emp.CalculateSalary(40,55);
emp.CalculateSalary(40,55)
Console.WriteLine(ID:{0},Name:{1},emp.id,emp.name);Console.WriteLine(Payment={0},weeklyPayment);
}
}
Give a link to the cls file
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 33/38
Repetition Loops The For Loop:
± Initialization; condition; increment/decrement;
Class ForLoop
{
static void Main(){
for(int counter=1;counter<=10;counter=counter+2)
{
Console.WriteLine(counter);}
}
}
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 34/38
Using Program Arguments
One possible form of the Main method is:
static void Main(string[]args)
Using this form allows the C# program toaccept as arguments a sequence of strings.
The arguments are received as string array
elements named
args[0],args[1],and so forth.
An Example : Program Arguments
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 35/38
Reversing an Array
In order to reverse an array, use the
statement:
Array.Reverse(myArray); Example : Reverse Array
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 36/38
Namespaces A namespace is a container that includes
classes and other types.
You place the class inside a namespace.
If two classes in two different namespaces
have the same name, you can refer to each
one by using the fully qualified name, for
example :
- MyNameSpace.Class1
- YourNameSpace.Class1
- Example : NameSpaces
8/8/2019 C Sharp (First Slide)
http://slidepdf.com/reader/full/c-sharp-first-slide 37/38
Using Properties
Properties expose a convenient public way for
reading and setting field values instead of
dealing directly with the fields.
One advantage of using properties as opposed
to using fields directly is that you can validate
the data before changing the value of the
field.
Example : Property Setting
Recommended