C Sharp (First Slide)

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 38

C# - In the beginning

The “Hello,World!” C# Program


//Example2-1.cs
//The first program in C#
Class HelloWorld
{
static void Main()
{
System.Console.WriteLine("Hello,World!");
}
}
//Example2-2.cs
//The second program in C#
usingSystem;
Class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello,World!");
}
}
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);
}
}
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 and
namespaces)
• Classes
• Structs(structures)
• Interfaces
• Delegates
• Enums(enumerations)
• Function members(such as methods, properties, indexers,
and so forth)
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.
Built – in Data Types
• bool • uint
• byte • long
• sbyte • ulong
• char • object
• decimal • short
• double • ushort
• float • string
• int
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
Variable Initialization
• intmyValue=123;
• intmyValue=0;
• intmyValue=newint();
Struct :
structPoint
{
intx;
inty;
}
Point myPoint=newPoint();
Reference Types
• A reference-type variable does not contain the
data itself;
• It actually contains the memory address of the
data.
• The following are the C# reference types:
– Class
– Interface
– Delegate
– Object
– String
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.
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
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=x–y;
• 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
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).
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 letter“D”
determines the number of decimal places in
the output.
The Fixed-point Format
• To display a number followed by a specified
number of decimal places, use “F”or“f”, 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
The General Format
• To display a number in the default format, use the
letter“G”or“g”like 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 follow the
statements, this is the same output produced by
no formatting at all.
• The statements are then equivalent to these
statements:
– Console.WriteLine("{0}",1.2);
– Console.WriteLine("{0}",1.23);
• There are scientific format and hexadecimal
formats.
• Do the following example for formats and you
can understand how C# handles them
• Example : Number Formats
The stringType
• String myString;
• String myString="Welcome to the string
world!";
• String myString="My friend, \nWelcome to
the string world!";
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!";
Reading the Keyboard Input
• To read input from the keyboard, use the .NET
method ReadLine.
• Ex : string myString=Console.ReadLine();
• Example : Keyboard input
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
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
Relational Operators
Operator Description

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

== Equal to

!= Not equal to

Example : Relational Operators


Logical Operators
Operator Description
&& AND(Short-circuit evaluation)
|| OR(Short-circuit evaluation)
& AND
| OR
! NOT

• Short – circuit evaluation : if one expression is


wrong, none of the following expression will be
evaluated.
•Ex: (x>5)&&(y==10)//false
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"); //The
Alternative result

Example : IfElse
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 evaluating
expression1 and 2.
• Example : ConditionalExpression
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)));
}
}
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
}
}
A First Look
//EmployeeDLL.cs  a class file
at the C# Code
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;
}
}
Let’s 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
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);
}
}
}
Using Program Arguments
• One possible form of the Main method is:
static void Main(string[]args)
• Using this form allows the C# program to
accept 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
Reversing an Array
• In order to reverse an array, use the
statement:
Array.Reverse(myArray);
• Example : Reverse Array
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
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
Read-only Fields
• Example : Read Only
• Inheritance  Example : Inheritance

You might also like