2.overview of c#
TRANSCRIPT
![Page 1: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/1.jpg)
Overview of C# Basic
![Page 2: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/2.jpg)
Contents
Introduction to C# Programing Structure of C# Create First Program using Console Application Class Data types and Variable Declaration Operators Decision making Statements
if,if else, if elseif,nested if Switch Case ? : (Ternary Operator)
Loops for while do while Foreach
![Page 3: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/3.jpg)
Introduction to C#
Language Created by Anders Hejlsberg (father of Delphi)
The Derivation History can be viewed here: http://www.levenez.com/lang/history.html
Principle Influencing Languages: C++ Delphi Java
C# Designed to be an optimal Windows development language
![Page 4: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/4.jpg)
Family of Languages
![Page 5: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/5.jpg)
C#- The Big Ideas
C# is the first “component oriented” language in the C/C++ family Class Properties Methods Events OOPs
![Page 6: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/6.jpg)
Robust and durable software
Garbage collection No memory leaks and stray pointers
Exceptions Error handling is not an afterthought
Type-safety No uninitialized variables, unsafe casts
Versioning Pervasive versioning considerations in all aspects of
language designNamespace (Packages in Java)
![Page 7: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/7.jpg)
![Page 8: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/8.jpg)
Its worth to note
C# is case sensitive.All statements and expression must end with
a semicolon (;).The program execution starts at the Main
method.Unlike Java, file name could be different from
the class name.
![Page 9: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/9.jpg)
Class,Memebers and Methods
Everything is encapsulated in a classCan have:
member data member methods
Class clsName { modifier dataType varName; modifier returnType methodName (params) {
statements; return returnVal;
} }
![Page 10: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/10.jpg)
Class Constructors
Automatically called when an object is instantiated:
public className(parameters){
statements;}
![Page 11: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/11.jpg)
Single inheritanceMultiple interface implementationClass members
Constants, fields, methods, properties, indexers, events, operators, constructors, destructors
Static and instance members Nested types
Member access public, protected, internal, private
![Page 12: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/12.jpg)
Hello World
using System;namespace Sample{
//Class public class HelloWorld { public HelloWorld() {
Constructor }
//Main method public static void Main(string[] args) { Console.WriteLine("Hello World!");
/* Comments in C# } }
}
![Page 13: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/13.jpg)
Compile & Execute a C# Program
If you are using Visual Studio.Net for compiling and executing C# programs, take the following steps:
Start Visual Studio. On the menu bar, choose File, New, Project. Choose Visual C# from templates, and then choose Windows. Choose Console Application. Specify a name for your project, and then choose the OK
button. The new project appears in Solution Explorer. Write code in the Code Editor. Click the Run button or the F5 key to run the project. A
Command Prompt window appears that contains the line Hello World.
![Page 14: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/14.jpg)
Data types and Variable Declaration
Value types Directly contain data Cannot be null
Reference types Contain references to objects May be null
int i = 123; string s = "Hello world";
123i
s "Hello world"
![Page 15: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/15.jpg)
Type System
Value types Primitives int i; Enums enum State { Off, On } Structs struct Point { int x, y; }
Reference types Classes class Foo: Bar, IFoo {...} Interfaces interface IFoo: IBar {...} Arrays string[] a = new string[10]; Delegates delegate void Empty();
![Page 16: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/16.jpg)
Structure
Like classes, except Stored in-line, not heap allocated Assignment copies data, not reference No inheritance
Ideal for light weight objects Complex, point, rectangle, color int, float, double, etc., are all structs
Benefits No heap allocation, less GC pressure More efficient use of memory
![Page 17: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/17.jpg)
Predefined Types
C# predefined types Reference object, string Signed sbyte, short, int, long Unsigned byte, ushort, uint, ulong Character char Floating-point float, double, decimal Logical bool
Predefined types are simply aliases for system-provided types For example, int == System.Int32
![Page 18: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/18.jpg)
Reserved Keywordsabstract as base Bool break byte casecatch char checked Class const continue decimaldefault delegate do double else enum eventexplicit extern false finally fixed float forforeach goto if implicit in in (generic
modifier)int
interface internal is lock long namespace newnull object operator out out
(genericmodifier)
override params
private protected public readonly ref return sbytesealed short sizeof stackalloc static string structswitch this throw true try typeof uintulong unchecked unsafe ushort using virtual voidvolatileadd alias ascending descending dynamic from getglobal group into join let orderby partial
(type)partial(method)
remove select set
![Page 19: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/19.jpg)
Using System // Namespaceclass Rectangle { // member variables declaration double length; double width; //Method public void Acceptdetails() { length = 10.5; //Assign values to variable width = 6.5; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//End class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle objRec = new Rectangle(); //Create Object of Class objRec.Acceptdetails();// Call method objRec.Display(); Console.ReadLine(); } }
![Page 20: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/20.jpg)
Operators
Arithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment Operators
![Page 21: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/21.jpg)
Arithmetic operators
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator increases integer value by one A++ will give 11
-- Decrement operator decreases integer value by one A-- will give 9
![Page 22: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/22.jpg)
Relational Operator
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.
![Page 23: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/23.jpg)
Logical operators
Operator
Description Example
&& Called Logical AND operator. If both the operands are non zero then condition becomes true.
(A && B) is false.
|| Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.
(A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is true.
![Page 24: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/24.jpg)
Bitwise OperatorsOperator Description Example
&Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) will give 12. which is 0000 1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) will give 49, which is 0011 0001
~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
(~A ) will give -61, which is 1100 0011 in 2's complement due to a signed binary number.
<<
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
A << 2 will give 240, which is 1111 0000
>>
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
A >> 2 will give 15, which is 0000 1111
![Page 25: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/25.jpg)
Assignment Operators
Operator
Description Example
=Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A
<<= Left shift AND assignment operatorC <<= 2 is same as C = C << 2
>>= Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operatorC &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2
![Page 26: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/26.jpg)
Operator Description Example
sizeof() Returns the size of a data type. sizeof(int), will return 4.
typeof() Returns the type of a class. typeof(StreamReader);
& Returns the address of an variable.
&a; will give actual address of the variable.
Other Operator
![Page 27: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/27.jpg)
Operators Precedence in C#
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
![Page 28: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/28.jpg)
Decision Making using C#
Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement(s) to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Statements If {…} If { …} else {…} If {….} else if{…} Nested if statements Switch () case : Ternary operator ( ?: )
![Page 29: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/29.jpg)
If Statement
An if statement consists of a boolean expression followed by one or more statements.
If(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
![Page 30: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/30.jpg)
If …else
• An if statement can be followed by an optional else statement, which executes when the boolean expression is false
if(boolean_expression){ /* statement(s) will execute if the boolean expression is true */}else{ /* statement(s) will execute if the boolean expression is false */}
![Page 31: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/31.jpg)
Nested IF
• You can use one if or else if statement inside another if or else if statement(s).
if( boolean_expression 1){ /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) { /* Executes when the boolean expression 2 is true */ }}
![Page 32: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/32.jpg)
Nested IF Exampleclass Program{ static void Main() {
SampleMethod1(50);SampleMethod2(50);SampleMethod3(50);
}
void SampleMethod1(int value) {
if (value >= 10){ if (value <= 100) {
Console.WriteLine(true); }}
}
void SampleMethod2(int value) {
if (value >= 10 && value <= 100){ Console.WriteLine(true);}
}
void SampleMethod3(int value) {
if (value <= 100 && value >= 10){ Console.WriteLine(true);}
}}
![Page 33: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/33.jpg)
Switch Case
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
switch(ch1) { case 'A': printf("This A is part of outer switch" ); switch(ch2) { case 'A': printf("This A is part of inner switch" ); break; case 'B': /* inner B case code */ } break; case 'B': /* outer B case code */}
![Page 34: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/34.jpg)
class SwitchTest{ static void Main() { Console.WriteLine("Coffee sizes: 1=small 2=medium 3=large"); Console.Write("Please enter your selection: "); string str = Console.ReadLine(); int cost = 0;
// Notice the goto statements in cases 2 and 3. The base cost of 25 // cents is added to the additional cost for the medium and large sizes. switch (str) { case "1": case "small": cost += 25; break; case "2": case "medium": cost += 25; goto case "1"; case "3": case "large": cost += 50; goto case "1"; default: Console.WriteLine("Invalid selection. Please select 1, 2, or 3."); break; } if (cost != 0) { Console.WriteLine("Please insert {0} cents.", cost); } Console.WriteLine("Thank you for your business."); }}
Switch Case Example
![Page 35: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/35.jpg)
The ? : Operator
We have covered conditional operator ? : in previous chapter which can be used to replace if...elsestatements. It has the following general form:
Exp1 ? Exp2 : Exp3;Where Exp1, Exp2, and Exp3 are
expressions. Notice the use and placement of the colon.
![Page 36: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/36.jpg)
Loops
A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages:
For(…) {};While() {}Do{…}While(…);forEach(…)
![Page 37: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/37.jpg)
For Loop
For loopFor loop is a repetition control structure that
allows you to efficiently write a loop that needs to execute a specific number of times.
for ( init; condition; increment/Decreament ){ statement(s);}
![Page 38: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/38.jpg)
Basic example of for loop
class Program { static void Main(string[] args) { /* for loop execution */ for (int a = 10; a < 20; a = a + 1) { Console.WriteLine("value of a: {0}", a); } Console.ReadLine(); } }
![Page 39: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/39.jpg)
While loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
while(condition) { statement(s); }
![Page 40: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/40.jpg)
Example of While
class WhileTest { static void Main() { int n = 2; while (n < 20) { Console.WriteLine("Current value of n is {0}", n); n+=2; } } }
![Page 41: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/41.jpg)
Do While
Like a while statement, except that it tests the condition at the end of the loop body
do{ statement(s);
}while( condition );
![Page 42: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/42.jpg)
Do While Example
public class TestDoWhile { public static void Main () { int x = 2; do { Console.WriteLine(x); x+=2; } while (x < 20); }}
![Page 43: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/43.jpg)
foreach
The foreach statement is used to iterate through the collection to get the information that you want
Does not use integer indexCan be use for Array,Collection , List,Class
Collection Returns each element in orderforeach (CollectionElementType name in Coll
ection) {
}
![Page 44: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/44.jpg)
ForEach example
class Program { static void Main(string[] args) { string[] arr = new string[5]; // declaring array //Storing value in array element arr[0] = “C#"; arr[1] = “C"; arr[2] = “C++"; arr[3] = “JAVA"; arr[4] = “Android"; //retrieving value using foreach loop foreach (string name in arr) { Console.WriteLine(“Working on" + name); } Console.ReadLine(); } }
![Page 45: 2.overview of c#](https://reader036.vdocuments.site/reader036/viewer/2022062418/5550c1f7b4c905ff618b5393/html5/thumbnails/45.jpg)
Questions ??