SlideShare a Scribd company logo
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
design
 Namespace (Packages in Java)
2.overview of c#
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 class
 Can 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 inheritance
 Multiple interface implementation
 Class 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 Keywords
abstract as base Bool break byte case
catch char checked Class const continue decimal
default delegate do double else enum event
explicit extern false finally fixed float for
foreach goto if implicit in in (generic
modifier)
int
interface internal is lock long namespace new
null object operator out out
(generic
modifier)
override params
private protected public readonly ref return sbyte
sealed short sizeof stackalloc static string struct
switch this throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
volatile
add alias ascending descending dynamic from get
global group into join let orderby partial
(type)
partial
(method)
remove select set
Using System // Namespace
class 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 Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment 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
Operato
r
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 Operators
Operator 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
Operat
or
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 operator
C <<= 2 is same as C
= C << 2
>>= Right shift AND assignment operator
C >>= 2 is same as C
= C >> 2
&= Bitwise AND assignment operator
C &= 2 is same as C
= C & 2
^= bitwise exclusive OR and assignment operator
C ^= 2 is same as C
= C ^ 2
|= bitwise inclusive OR and assignment operator
C |= 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 Example
class 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 loop
 For 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 index
 Can be use for Array,Collection , List,Class Collection
 Returns each element in order
 foreach (CollectionElementType name in Collection)
{
 }
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 ??

More Related Content

PPSX
C++ Programming Language
PDF
Learn Java Part 2
PPTX
Intro to c++
PDF
Python unit 2 as per Anna university syllabus
PPT
PDF
PPTX
Introduction to Selection control structures in C++
C++ Programming Language
Learn Java Part 2
Intro to c++
Python unit 2 as per Anna university syllabus
Introduction to Selection control structures in C++

What's hot (18)

PPTX
Ch6 Loops
PDF
ODP
(2) c sharp introduction_basics_part_i
PPT
C++ Language
PPTX
What is c
PDF
Python Unit 3 - Control Flow and Functions
PPT
PPT
PDF
PPT
04 control structures 1
PPT
Control Statements, Array, Pointer, Structures
DOCX
C# language basics (Visual studio)
PPTX
Introduction to Basic C programming 02
PPTX
Programming Fundamentals
PPT
Getting started with c++
PDF
Logical Expressions in C/C++. Mistakes Made by Professionals
PPTX
Ch7 Basic Types
PPTX
Operators in java
Ch6 Loops
(2) c sharp introduction_basics_part_i
C++ Language
What is c
Python Unit 3 - Control Flow and Functions
04 control structures 1
Control Statements, Array, Pointer, Structures
C# language basics (Visual studio)
Introduction to Basic C programming 02
Programming Fundamentals
Getting started with c++
Logical Expressions in C/C++. Mistakes Made by Professionals
Ch7 Basic Types
Operators in java
Ad

Viewers also liked (20)

PPTX
Tom van Ees - Academic and Commercial software Development
PDF
PHP Database Connections to MYSQL
PDF
Dijkstra
PPTX
C# language
PPT
Php with MYSQL Database
PPT
Dot net guide for beginner
PPTX
C sharp
PPT
C++ to java
PPTX
Python basic
PPTX
Beginning Java for .NET developers
PDF
A comparison between C# and Java
PPT
Php i basic chapter 3
PPSX
Microsoft C# programming basics
PPT
Difference between C++ and Java
PPT
Basics of c# by sabir
PPTX
C sharp
PPTX
C vs c++
PPT
ASP.NET Session 1
Tom van Ees - Academic and Commercial software Development
PHP Database Connections to MYSQL
Dijkstra
C# language
Php with MYSQL Database
Dot net guide for beginner
C sharp
C++ to java
Python basic
Beginning Java for .NET developers
A comparison between C# and Java
Php i basic chapter 3
Microsoft C# programming basics
Difference between C++ and Java
Basics of c# by sabir
C sharp
C vs c++
ASP.NET Session 1
Ad

Similar to 2.overview of c# (20)

PPTX
C sharp part 001
PPTX
Programming presentation
PPT
Beginning with C++.ppt thus us beginnunv w
PDF
C# Fundamentals - Basics of OOPS - Part 2
PPT
C++ chapter 2
DOCX
C# language basics (Visual Studio)
PPTX
PPS
C programming session 02
PPTX
CSE113 (UNIT-2)Storage classes in the computer science.pptx
PPTX
03. operators and-expressions
PPT
C program
PPTX
Vb script final pari
PPS
Programming in Arduino (Part 1)
PPTX
Microcontroller lec 3
PPT
c_tutorial_2.ppt
PPTX
3 operators-expressions-and-statements-120712073351-phpapp01
PPTX
3 operators-expressions-and-statements-120712073351-phpapp01
PPT
03 Operators and expressions
PDF
C-PPT.pdf
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
C sharp part 001
Programming presentation
Beginning with C++.ppt thus us beginnunv w
C# Fundamentals - Basics of OOPS - Part 2
C++ chapter 2
C# language basics (Visual Studio)
C programming session 02
CSE113 (UNIT-2)Storage classes in the computer science.pptx
03. operators and-expressions
C program
Vb script final pari
Programming in Arduino (Part 1)
Microcontroller lec 3
c_tutorial_2.ppt
3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
03 Operators and expressions
C-PPT.pdf
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’

More from Raghu nath (20)

PPTX
Mongo db
PDF
Ftp (file transfer protocol)
PDF
MS WORD 2013
PDF
Msword
PDF
Ms word
PDF
Javascript part1
PDF
Regular expressions
PDF
Selection sort
PPTX
Binary search
PPTX
JSON(JavaScript Object Notation)
PDF
Stemming algorithms
PPTX
Step by step guide to install dhcp role
PPTX
Network essentials chapter 4
PPTX
Network essentials chapter 3
PPTX
Network essentials chapter 2
PPTX
Network essentials - chapter 1
PPTX
Python chapter 2
PPTX
python chapter 1
PPTX
Linux Shell Scripting
PPTX
Mongo db
Ftp (file transfer protocol)
MS WORD 2013
Msword
Ms word
Javascript part1
Regular expressions
Selection sort
Binary search
JSON(JavaScript Object Notation)
Stemming algorithms
Step by step guide to install dhcp role
Network essentials chapter 4
Network essentials chapter 3
Network essentials chapter 2
Network essentials - chapter 1
Python chapter 2
python chapter 1
Linux Shell Scripting

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Cloud computing and distributed systems.
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Encapsulation theory and applications.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Approach and Philosophy of On baking technology
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPT
Teaching material agriculture food technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
Unlocking AI with Model Context Protocol (MCP)
Dropbox Q2 2025 Financial Results & Investor Presentation
Cloud computing and distributed systems.
sap open course for s4hana steps from ECC to s4
Encapsulation theory and applications.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Approach and Philosophy of On baking technology
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Electronic commerce courselecture one. Pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
The AUB Centre for AI in Media Proposal.docx
Teaching material agriculture food technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Spectroscopy.pptx food analysis technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf

2.overview of c#

  • 2. 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
  • 3. 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
  • 5. C#- The Big Ideas  C# is the first “component oriented” language in the C/C++ family  Class  Properties  Methods  Events  OOPs
  • 6. 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 design  Namespace (Packages in Java)
  • 8. 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.
  • 9. Class,Memebers and Methods  Everything is encapsulated in a class  Can have:  member data  member methods Class clsName { modifier dataType varName; modifier returnType methodName (params) { statements; return returnVal; } }
  • 10. Class Constructors  Automatically called when an object is instantiated: public className(parameters) { statements; }
  • 11.  Single inheritance  Multiple interface implementation  Class members  Constants, fields, methods, properties, indexers, events, operators, constructors, destructors  Static and instance members  Nested types  Member access  public, protected, internal, private
  • 12. 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# } } }
  • 13. 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.
  • 14. 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"
  • 15. 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();
  • 16. 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
  • 17. 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
  • 18. Reserved Keywords abstract as base Bool break byte case catch char checked Class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in in (generic modifier) int interface internal is lock long namespace new null object operator out out (generic modifier) override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile add alias ascending descending dynamic from get global group into join let orderby partial (type) partial (method) remove select set
  • 19. Using System // Namespace class 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(); } }
  • 20. Operators  Arithmetic Operators  Relational Operators  Logical Operators  Bitwise Operators  Assignment Operators
  • 21. 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
  • 22. 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.
  • 23. Logical operators Operato r 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.
  • 24. Bitwise Operators Operator 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
  • 25. Assignment Operators Operat or 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 operator C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator C &= 2 is same as C = C & 2 ^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2 |= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
  • 26. 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
  • 27. 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
  • 28. 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 ( ?: )
  • 29. 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 */ }
  • 30. 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 */ }
  • 31. 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 */ } }
  • 32. Nested IF Example class 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); } } }
  • 33. 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 */ }
  • 34. 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
  • 35. 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.
  • 36. 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(…)
  • 37. For Loop  For loop  For 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);  }
  • 38. 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(); } }
  • 39. 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); }
  • 40. 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; } } }
  • 41. Do While  Like a while statement, except that it tests the condition at the end of the loop body  do  {  statement(s);  }while( condition );
  • 42. Do While Example public class TestDoWhile { public static void Main () { int x = 2; do { Console.WriteLine(x); x+=2; } while (x < 20); } }
  • 43. foreach  The foreach statement is used to iterate through the collection to get the information that you want  Does not use integer index  Can be use for Array,Collection , List,Class Collection  Returns each element in order  foreach (CollectionElementType name in Collection) {  }
  • 44. 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(); } }