Overview of C# Basic
Overview of C# Basic
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
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
Family of Languages
C#- The Big Ideas
C# is the first “component oriented” language in the C/C++ family Class Properties Methods Events OOPs
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)
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.
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;
} }
Class Constructors
Automatically called when an object is instantiated:
public className(parameters){
statements;}
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
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# } }
}
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.
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"
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();
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
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
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
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(); } }
Operators
Arithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment Operators
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
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.
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.
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
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
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
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
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 ( ?: )
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 */
}
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 */}
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 */ }}
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);}
}}
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 */}
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
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.
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(…)
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);}
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(); } }
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); }
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; } } }
Do While
Like a while statement, except that it tests the condition at the end of the loop body
do{ statement(s);
}while( condition );
Do While Example
public class TestDoWhile { public static void Main () { int x = 2; do { Console.WriteLine(x); x+=2; } while (x < 20); }}
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) {
}
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(); } }
Questions ??