0% found this document useful (0 votes)
37 views

Fundaments of C Sharp Note 1

Uploaded by

nisalbosa123
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Fundaments of C Sharp Note 1

Uploaded by

nisalbosa123
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 116

Visual Studio -

C# Programming
.Net Framework Overview
VB C++ C# JScript …

Common Language Specification

Web Forms
Win Forms
(ASP.NET)
Visual Studio.NET

Ado.Net and XML

Base Class Library

Common Language Runtime


Introduction to C#
Goals of the C# language
 A simple, modern, general-purpose object-oriented
langauge
 Software robustness and programmer productivity
◦ Strong type checking, array bounds checking, detection of
use of uninitialized variables, source code portability,
automatic garbage collection
 Useable in creating software components
 Ease of learning by programmers familiar with C++
and Java
 Usable for embedded and large
system programming
 Strong performance, but not
intended to compete with C
or assembly language
Type II safety cans for flammables
Brief history of C#
 Originated by Microsoft as a
response to Java
◦ Initial public release in 2000
 Language name inspired by musical note C#
◦ A “step above” C/C++ (and Java)
◦ Linux wags: Db (D-flat, same note, different name)
 Lead designers: Anders Hejlsberg, Scott
Wiltamuth
◦ Hejlsberg experience: Turbo Pascal, Borland Delphi,
J++
 C# standardized via ECMA and ISO
◦ However, Microsoft retains architectural control
Key language features
 Unified object system
◦ Everything type is an object,
even primitives
 Single inheritance
 Interfaces
◦ Specify methods & interfaces,
but no implementation
 Structs cking, Flickr
www.flickr.com/photos/spotsgot/1414345/

◦ A restricted, lightweight (efficient) type


 Delegates
◦ Expressive typesafe function pointer
◦ Useful for strategy and observer design patterns
 Preprocessor directives
C# Features
 Simple
 Modern
 Object-Oriented
 Type-safe
 Versionable
 Compatible
 Secure

7
Strong Programming Features of C#

 Although C# constructs closely follow


traditional high-level languages, C and C+
+ and being an object-oriented
programming language.
 It has strong resemblance with Java, it has

numerous strong programming features


that make it endearing to a number of
programmers worldwide.

8
Strong Programming Features of C#

Following is the list of few important features of C# −

 Boolean Conditions
 Automatic Garbage Collection
 Standard Library
 Assembly Versioning
 Properties and Events
 Delegates and Events Management
 Easy-to-use Generics
 Indexers
 Conditional Compilation
 Simple Multithreading
 LINQ and Lambda Expressions
 Integration with Windows
9
Creating Hello World Program
 A C# program consists of the following parts

◦ Namespace declaration
◦ A class
◦ Class methods
◦ Class attributes
◦ A Main method
◦ Statements and Expressions
◦ Comments
Creating Hello World Program
using System;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled and executed, it produces
the following result −
Hello World
Creating Hello World Program
Let us look at the various parts of the given program −
 The first line of the program using System; - the using
keyword is used to include the System namespace in
the program. A program generally has multiple using
statements.
 The next line has the namespace declaration. A
namespace is a collection of classes. The
HelloWorldApplication namespace contains the class
HelloWorld.
 The next line has a class declaration, the class
HelloWorld contains the data and method definitions
that your program uses. Classes generally contain
multiple methods. Methods define the behavior of the
class. However, the HelloWorld class has only one
method Main.
Creating Hello World Program
Let us look at the various parts of the given program −
 Thenext line defines the Main method, which is the
entry point for all C# programs. The Main method states
what the class does when executed.
 The next line /*...*/ is ignored by the compiler and it is
put to add comments in the program.
 TheMain method specifies its behavior with the
statement Console.WriteLine("Hello World");
Creating Hello World Program
Let us look at the various parts of the given program −
 WriteLine
is a method of the Console class defined in
the System namespace. This statement causes the
message "Hello, World!" to be displayed on the screen.
 Thelast line Console.ReadKey(); is for the VS.NET Users.
This makes the program wait for a key press and it
prevents the screen from running and closing quickly
when the program is launched from Visual Studio .NET.
Syntax
 Case-sensitive
 Whitespace has no meaning
◦ Sequences of space, tab, linefeed,
carriage return
 Semicolons are used to
terminate statements (;)
 Curly braces {} enclose
code blocks
 Unlike Java, program file name could be different
from the class name.
Visual Studio 2017 IDE

Microsoft has introduced Visual Studio.NET,


which is a tool (also called Integrated Development
Environment) for developing .NET applications by
using programming languages such as VB, C#, VC++
and VJ#. etc.

16
Using Visual Studio.NET
 Types of projects
◦ Console Application
◦ Windows Application
◦ Web Application
◦ Web Service
◦ Windows Service
◦ Class Library
◦ ...
Using Visual Studio.NET
 Windows
◦ Solution Explorer
◦ Class View
◦ Properties
◦ Output
◦ Task List
◦ Object Browser
◦ Server Explorer
◦ Toolbox
Using Visual Studio.NET
 Building
 Debugging

◦ Break points
 References
 Saving
Using Visual Studio.NET
Compiling and Executing the 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.
Using Visual Studio.NET
 Compiling and Executing the Program continued…

 if you are using Visual Studio.Net for compiling and executing C# programs, take
the following steps −

 Choose Console Application.

 Specify a name for your project and click OK button.

 This creates a new project in Solution Explorer.

 Write code in the Code Editor.

 Click the Run button or press F5 key to execute the project. A


Command Prompt window appears that contains the line Hello World.
Using Visual Studio.NET
 Compiling and Executing the Program continued…

 if you are using Visual Studio.Net for compiling and executing C# programs,
take the following steps −

 Choose Console Application.

 Specify a name for your project and click OK button.

 This creates a new project in Solution Explorer.

 Write code in the Code Editor.

 Click the Run button or press F5 key to execute the project. A


Command Prompt window appears that contains the line Hello
World.
Using Visual Studio.NET
 You can compile a C# program by using the command-line instead of the
Visual Studio IDE −

 Open a text editor and add the above-mentioned code.

 Save the file as helloworld.cs

 Open the command prompt tool and go to the directory where you
saved the file.

 Type csc helloworld.cs and press enter to compile your code.

 If there are no errors in your code, the command prompt takes you
to the next line and generates helloworld.exe executable file.

 Type helloworld to execute your program.

 You can see the output Hello World printed on the screen.
Statements, Expressions, Variables
and Data types
Statements & Expressions
 Statements
 are used to accomplish simplest
tasks in C#
 forms simplest C# operations.
 can be single line or Span to
multiple lines.
 does not necessarily return a
value.
CS 1001 25
Statements & Expressions Contd...

 Each statement is terminated with a “;”.


 Compound or Block statements can be

used and they are surrounded by curly


braces ({ }).
 Eg. Block Statement
Simple Statements if (a>b) {
int i=5;
int i=5;
i=i++;
String name=“Kasun”;
}
using system;
CS 1001 26
Statements & Expressions Contd...
 Expressions
◦ Simplest form of Statements
◦ returns a value when evaluated.
◦ Can be assigned to a variable or can be tested in C#
statements.
◦ Most expressions are a combination of Operators &
Operands

CS 1001 27
Statements & Expressions Contd...
 Examples for expressions
Result is assigned to
variable

areaOfCircle = (3.14*radius*radius);
Expression
Expressions in Test Conditions
if (num1 > num2)
CS 1001 28
Comments
 Can be used to document what the program does
and what specific blocks or lines of code do.
 The C# compiler ignores comments
 You can include them anywhere in a program
without affecting your code.
◦ Single line comments
// for single line comments

◦ Multiple line comments


/* for multi line comments */

◦ XML tags comments


/// XML tags displayed in a code comment
Variables in C#
 A variable is nothing but a name given to a
storage area that our programs can
manipulate.
 Each variable in C# has a specific type, which

determines the size and layout of the


variable's memory the range of values that
can be stored within that memory and the set
of operations that can be applied to the
variable.
Variables in C#
 The variables in C#, are categorized
into the following types −
◦ Value types
◦ Reference types
◦ Pointer types
Variables in C#
 The basic value types provided in C# can be
categorized as −
Type Example
sbyte, byte, short, ushort, int, uint,
Integral types
long, ulong, and char
Floating point types float and double
Decimal types decimal
Boolean types true or false values, as assigned
Nullable types Nullable data types
C# also allows defining other value types of
variable such as enum and reference types of
variables
Variables in C#
C# Data Types and Value Ranges
All minimum and maximum values can be
found using (data type).MinValue and (data
type).MaxValue (e.g. int.MinValue).
Variables in C#
Type Bytes Description Minimum Maximum Example

bool 1 Named literal false true

sbyte 1 Signed byte -128 127

byte 1 Unsigned byte 0 255

Signed short
short 2 -32768 32767
integer

Unsigned
ushort 2 0 65535
short

int 4 Signed integer -2147483648 2147483647

Unsigned
uint 4 0 4294967295
integer

long 8 Signed long int -9.2233E+18 9.2233E+18


Variables in C#
Unsigned 18446E+1
ulong 8 0
long int 9
Unicode
character,
contained
char 2 0 128 a,b,4
within
single
quotes.
-
floating 3.402823E
float 4 3.402823E 3.14159
point +38
+38
-
Floating 1.7976931
double 8 1.7976931 3.14159
point E+308
E+308
Variables in C#
Floating point,
accurate to the
decimal 16 -7.9228E+24 7.9228E+24
28th decimal
place.

Base type for all


object 8+ n/a n/a n/a
other types

Immutable
string 20+ n/a n/a "Hello World"
character array

Represents an
instant in time,
typically 00:00:00 23:59:59 14:289:35
DateTime 8
expressed as a 01/01/0001 31/12/9999 08/05/2010
date and time of
day.
Variables in C#
 To get the exact size of a type or a variable
on a particular platform, you can use the
sizeof method.

The expression sizeof(type)

yields the storage size of the object or type in


bytes.
Variables in C#
Following is an example to get the size of int type on any
machine −

using System;

namespace DataTypeApplication {
class Program {
static void Main(string[] args) {
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
Variables in C#
Following is an example to get the size of int type on any
machine −

using System;

namespace DataTypeApplication {
class Program {
static void Main(string[] args) {
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
Variables in C#
Reference Type
 The reference types do not contain the actual

data stored in a variable, but they contain a


reference to the variables.
 In other words, they refer to a memory location.

 Using multiple variables, the reference types

can refer to a memory location.


 If the data in the memory location is changed

by one of the variables, the other variable


automatically reflects this change in value.
Example of built-in reference types are: object,
dynamic, and string.
Variables in C#
Object Type

The Object Type is the ultimate base class for all data types
in C# Common Type System (CTS). Object is an alias for
System.Object class. The object types can be assigned
values of any other types, value types, reference types,
predefined or user-defined types. However, before
assigning values, it needs type conversion.

When a value type is converted to object type, it is called


boxing and on the other hand, when an object type is
converted to a value type, it is called unboxing.

object obj;
obj = 100; // this is boxing
Variables in C#
Dynamic Type

You can store any type of value in the dynamic data type variable.
Type checking for these types of variables takes place at run-time.

Syntax for declaring a dynamic type is −

dynamic <variable_name> = value;

For example,

dynamic d = 20;

Dynamic types are similar to object types except that type checking
for object type variables takes place at compile time, whereas that
for the dynamic type variables takes place at run time.
Variables in C#
String Type

The String Type allows you to assign any string values to a variable. The
string type is an alias for the System.String class. It is derived from
object type. The value for a string type can be assigned using string
literals in two forms: quoted and @quoted.

For example,

String str = "Tutorials Point";

A @quoted string literal looks as follows −

@"Tutorials Point";

The user-defined reference types are: class,


interface, or delegate.
Variables in C#
Pointer Type

Pointer type variables store the memory address of


another type. Pointers in C# have the same capabilities
as the pointers in C or C++.

Syntax for declaring a pointer type is −

type* identifier;

For example,

char* cptr;
int* iptr;
Variables in C#
 Defining Variables
◦ <data_type> <variable_list>;

• Some valid variable definitions are shown here −

int i, j, k;
char c, ch;
float f, salary;
double d;
• You can initialize a variable at the time of definition as −

int i = 100;
Variables in C#
Initializing Variables
 The general form of initialization is −

variable_name = value;
 Variables can be initialized in their declaration.
<data_type> <variable_name> = value;

int d = 3, f = 5; /* initializing d and f. */


byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an
approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'.
*/
Variables in C#
Initializing Variables

using System;

namespace VariableDefinition {
class Program {
static void Main(string[] args) {
short a;
int b ;
double c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
Variables in C#
Accepting Values from User

The Console class in the System namespace


provides a function ReadLine() for accepting
input from the user and store it into a
variable.
For example,

int num;
num = Convert.ToInt32(Console.ReadLine());
Variables in C#
Accepting Values from User

 The function Convert.ToInt32() converts the


data entered by the user to int data type,
because Console.ReadLine() accepts the data
in string format.
Accepting Values from User
Variables in C# Lvalue and Rvalue Expressions
in C#

There are two kinds of expressions in C# −

lvalue − An expression that is an lvalue


may appear as either the left-hand or right-
hand side of an assignment.

rvalue − An expression that is an rvalue


may appear on the right- but not left-hand
side of an assignment.
Variable declaration may be:

Explicit − int number = 8;


char ch=’A’;

implicit − var num=10;


Constants in C#
 Constants are values which are fixed and
cannot be changed anytime during program
execution. They can be of any data type.

const float fl= 2.511;


public const int months = 12;
const int months = 12, weeks = 52, days = 365;
Literals in C#

 Literal is a source code representation of


a value, i.e. it is a value that has been
hard-coded directly into your source.
Example
 x is a variable, and 100 is a literal.
Literals in C#

 Type of literals in C# are:


1. Boolean Literal
2. Integer Literal
3. Real Literal
4. Character Literal
5. String Literal
6. Null Literal
Literals in C#

1. Boolean Literal
 There are two Boolean literal values:

true and false.

Example:

bool open = true;


Literals in C#
1. Integer Literal
 Integer literals are used to write values of types
int, uint, long, and ulong. Integer literals have
two possible forms: decimal and hexadecimal.
 Example

100 //decimal
0x123f //hexadecimal
072 //octal
1000 //integer
100u //uint
1000 //long
10ul //ulong
Literals in C#
 Real Literal
 Real literals are used to write values of types

float, double, and decimal.


Example

10.15 //double
100.72f //float
1.45d //double
1.44m //decimal
e23 //exponent. Means 1023
Literals in C#
 Character Literal

 A character literal represents a single


character, and usually consists of a character
in quotes, as in 'a'.
Literals in C#
 Example – Escape sequences
Literals in C#
 String literals

 C# supports two forms of string


literals: regular string literals and
verbatim string literals .
 A regular string literal consists of zero

or more characters enclosed in double


quotes, as in "string", and may include
both simple escape sequences (such as
\t for the tab character) and
hexadecimal and Unicode escape
sequences.
Literals in C#
 String literals

 A verbatim string literal consists of an


@ character followed by a double-quote
character, zero or more characters, and
a closing double-quote character.
 They can store characters or escape

sequences. A simple example is


@"string".
Literals in C#
 String literals

Examples:
string a = "string, literal"; // string,
literal
string b = @"string, literal"; // string,
literal
string c = "string \t literal"; // string
literal
string d = @"string \t literal"; //
string \t literal
Literals in C#
Null Literals

 Null Literal is literal that denotes null type.


 Moreover, null can fit to any reference-
type . and hence is a very good example
for polymorphism.

Examples:

int x = null;
if (x == null)
Console.WriteLine("This is null");
Enumeration in C#
 An enumeration is used in any
programming language to define a
constant set of values.
 For example, the days of the week can

be defined as an enumeration and used


anywhere in the program.
 The enumeration is defined with the

help of the keyword 'enum'.

public enum Days { Monday, Tuesday,


Wednesday, Thursday, Friday, Saturday, Sunday
}
Enumeration in C#
using System;

namespace ConsoleApplication1{
public enum Days { Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday }

class Program {
static void Main(string[] args) {
Days day = Days.Monday;
Console.WriteLine((int)day);
Console.ReadLine();
}
}
}
Enumeration in C#

static void Main(string[] args)


{
string[] values =
Enum.GetNames(typeof(Days));
foreach(string s in values)
Console.WriteLine(s);

Console.ReadLine();
}
Operators in C#
 Operators are symbols that are used to
perform operations on operands. Operands
may be variables and/or constants.
 For example, in 2+3, + is an operator that is

used to carry out addition operation, while 2


and 3 are operands.
 Operators are used to manipulate variables

and values in a program.


 C# supports a number of operators that are

classified based on the type of operations


they perform.
Operators in C#
 Basic Assignment Operator

◦ Basic assignment operator (=) is used to assign


values to variables. For example,

double x;
x = 50.05;

int a=5,c,b,d;
c=d=b=a;
Operators in C#
 Basic Assignment Operator

using System;

namespace Operator{
class AssignmentOperator {
public static void Main(string[] args) {
int firstNumber, secondNumber;
// Assigning a constant to variable
firstNumber = 10;
Console.WriteLine("First Number = {0}", firstNumber);
// Assigning a variable to another variable
secondNumber = firstNumber;
Console.WriteLine("Second Number = {0}", secondNumber);
}
}
}
Operators in C#
 Basic Assignment Operator

◦ You might have noticed the use of curly brackets { }


in the example.

◦ {0} is replaced by the first variable that follows the


string, {1} is replaced by the second variable and so
on.
Operators in C#
 Arithmetic Operators

 Arithmetic operators are used to perform


arithmetic operations such as addition,
subtraction, multiplication, division, etc.

For example,

int x = 5;
int y = 10;
int z = x + y;// z = 15
Operators in C#
C# Arithmetic Operators

Operator Operator Name Example

+ Addition Operator 6 + 3 evaluates to 9

- Subtraction Operator 10 - 6 evaluates to 4

* Multiplication Operator 4 * 2 evaluates to 8

/ Division Operator 10 / 5 evaluates to 2

Modulo Operator
% 16 % 3 evaluates to 1
(Remainder)
Operators in C#
using System;
namespace Operator{
class ArithmeticOperator {
public static void Main(string[] args){
double firstNumber = 14.40, secondNumber = 4.60, result;
int num1 = 26, num2 = 4, rem;
result = firstNumber + secondNumber;
Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber, result);
result = firstNumber - secondNumber;
Console.WriteLine("{0} - {1} = {2}", firstNumber, secondNumber, result);

result = firstNumber * secondNumber;


Console.WriteLine("{0} * {1} = {2}", firstNumber, secondNumber, result);

result = firstNumber / secondNumber;


Console.WriteLine("{0} / {1} = {2}", firstNumber, secondNumber, result);

rem = num1 % num2;


Console.WriteLine("{0} % {1} = {2}", num1, num2, rem);
}
}
}
Operators in C#
Relational Operators

Relational operators are used to check the relationship between two


operands. If the relationship is true the result will be true, otherwise it
will result in false.

Relational operators are used in decision making and loops.


Operators in C#
Relational Operators

C# Relational Operators
Operator Operator Name Example

== Equal to 6 == 4 evaluates to false

> Greater than 3 > -1 evaluates to true

< Less than 5 < 3 evaluates to false

>= Greater than or equal to 4 >= 4 evaluates to true

<= Less than or equal to 5 <= 3 evaluates to false

!= Not equal to 10 != 2 evaluates to true


Operators in C#
using System;
namespace Operator{
class RelationalOperator {
public static void Main(string[] args){
bool result;
int firstNumber = 10, secondNumber = 20;
result = (firstNumber==secondNumber);
Console.WriteLine("{0} == {1} returns {2}",firstNumber, secondNumber, result);

result = (firstNumber > secondNumber);


Console.WriteLine("{0} > {1} returns {2}",firstNumber, secondNumber, result);

result = (firstNumber < secondNumber);


Console.WriteLine("{0} < {1} returns {2}",firstNumber, secondNumber, result);

result = (firstNumber >= secondNumber);


Console.WriteLine("{0} >= {1} returns {2}",firstNumber, secondNumber, result);

result = (firstNumber <= secondNumber);


Console.WriteLine("{0} <= {1} returns {2}",firstNumber, secondNumber, result);

result = (firstNumber != secondNumber);


Console.WriteLine("{0} != {1} returns {2}",firstNumber, secondNumber, result);
}
}
}
Operators in C#
Logical Operators

 Logical operators are used to perform logical


operation such as and, or.
 Logical operators operates on boolean expressions
(true and false) and returns boolean values.
 Logical operators are used in decision making and
loops.
Operators in C#
Here is how the result is evaluated for logical AND
and OR operators.
C# Logical operators

Operand 1 Operand 2 OR (||) AND (&&)

true true true true

true false true false

false true true false

false false false false

In simple words, the table can be summarized as:

If one of the operand is true, the OR operator will evaluate it to true.


If one of the operand is false, the AND operator will evaluate it to false.
Operators in C#
using System;

namespace Operator{
class LogicalOperator{
public static void Main(string[] args) {
bool result;
int firstNumber = 10, secondNumber = 20;

// OR operator
result = (firstNumber == secondNumber) || (firstNumber > 5);
Console.WriteLine(result);

// AND operator
result = (firstNumber == secondNumber) && (firstNumber > 5);
Console.WriteLine(result);
}
}
}
Operators in C#
! Logical Negation (Not) Inverts the value of a boolean

using System;

namespace Operator
{
class UnaryOperator
{
public static void Main(string[] args)
{
bool flag = true;

Console.WriteLine("!flag = " + (!flag));


}
}
}
Operators in C#
Unary Operators
Unlike other operators, the unary operators operates on a single operand.

C# unary operators
Operator Operator Name Description

+ Unary Plus Leaves the sign of


operand as it is
- Unary Minus Inverts the sign of
operand
++ Increment Increment value by 1
-- Decrement Decrement value by 1
Operators in C#
using System;
namespace Operator{
class UnaryOperator{
public static void Main(string[] args){
int number = 10, result;

result = +number;
Console.WriteLine("+number = " + result);

result = -number;
Console.WriteLine("-number = " + result);

result = ++number;
Console.WriteLine("++number = " + result);

result = --number;
Console.WriteLine("--number = " + result);
}
}
}
Operators in C#
 The increment (++) and decrement (--) operators
can be used as prefix and postfix.

 If used as prefix, the change in value of variable is


seen on the same line

 if used as postfix, the change in value of variable is


seen on the next line.
Operators in C# 10
using System; 11
12
12
namespace Operator{
class UnaryOperator {
public static void Main(string[] args)
{
int number = 10;

Console.WriteLine((number++));
Console.WriteLine((number));

Console.WriteLine((++number));
Console.WriteLine((number));
}
}
}
Operators in C#
We can see the effect of using ++ as prefix and postfix. When
++ is used after the operand, the value is first evaluated and
then it is incremented by 1. Hence the statement

Console.WriteLine((number++));

prints 10 instead of 11. After the value is printed, the value of


number is incremented by 1.

The process is opposite when ++ is used as prefix. The value


is incremented before printing. Hence the statement

Console.WriteLine((++number));

prints 12.

The case is same for decrement operator (--).


Operators in C#
Ternary Operator
 The ternary operator ? : operates on three

operands.
 It is a shorthand for if-then-else statement.

Ternary operator can be used as follows:

variable = Condition? Expression1 : Expression2;

The ternary operator works as follows:

◦ If the expression stated by Condition is true, the result of


Expression1 is assigned to variable.
◦ If it is false, the result of Expression2 is assigned
to variable.
Operators in C#
using System;

namespace Operator
{
class TernaryOperator
{
public static void Main(string[] args)
{
int number = 10;
string result;
result = (number % 2 == 0)? "Even " : "Odd ";
Console.WriteLine("{0} is {1}", number, result);
}
}
}
Operators in C#

# Bitwise and Bit Shift operators

Operator Operator Name


~ Bitwise Complement
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Bitwise Left Shift
>> Bitwise Right Shift
Operators in C#
using System;
namespace Operator{
class BitOperator{
public static void Main(string[] args){
int firstNumber = 10;
int secondNumber = 20;
int result;
result = ~firstNumber;
Console.WriteLine("~{0} = {1}", firstNumber, result);

result = firstNumber & secondNumber;


Console.WriteLine("{0} & {1} = {2}", firstNumber,secondNumber, result);

result = firstNumber | secondNumber;


Console.WriteLine("{0} | {1} = {2}", firstNumber,secondNumber, result);

}
}
}
Operators in C#
using System;

namespace Operator{
class BitOperator {
public static void Main(string[] args) {
int firstNumber = 10;
int secondNumber = 20;
int result;
result = firstNumber ^ secondNumber;
Console.WriteLine("{0} ^ {1} = {2}", firstNumber,secondNumber, result);
result = firstNumber << 2;
Console.WriteLine("{0} << 2 = {1}", firstNumber, result);
result = firstNumber >> 2;
Console.WriteLine("{0} >> 2 = {1}", firstNumber, result);
}
}
}
Operators in C#
Compound Assignment Operators

C# Compound Assignment Operators


Operato Equivalent
Operator Name Example
r To

+= Addition Assignment x += 5 x=x+5

-= Subtraction Assignment x -= 5 x=x-5

*= Multiplication Assignment x *= 5 x=x*5

/= Division Assignment x /= 5 x=x/5

%= Modulo Assignment x %= 5 x=x%5

&= Bitwise AND Assignment x &= 5 x=x&5


Operators in C#
Compound Assignment Operators

C# Compound Assignment Operators


Operator Operator Name Example Equivalent To

|= Bitwise OR Assignment x |= 5 x=x|5

^= Bitwise XOR Assignment x ^= 5 x=x^5

<<= Left Shift Assignment x <<= 5 x = x << 5

>>= Right Shift Assignment x >>= 5 x = x >> 5

=> Lambda Operator x => x*x Returns x*x


Operators in C#
using System;
namespace Operator{
class BitOperator {
public static void Main(string[] args) {
int number = 10;
number += 5;
Console.WriteLine(number);
number -= 3;
Console.WriteLine(number);
number *= 2;
Console.WriteLine(number);
number /= 3;
Console.WriteLine(number);
number %= 3;
Console.WriteLine(number);
Operators in C#
number &= 10;
Console.WriteLine(number);

number |= 14;
Console.WriteLine(number);

number ^= 12;
Console.WriteLine(number);

number <<= 2;
Console.WriteLine(number);

number >>= 3;
Console.WriteLine(number);
}
}
}
Operators in C#
Casting and Type Conversions

 Because C# is statically-typed at compile time,


after a variable is declared, it cannot be declared
again or used to store values of another type
unless that type is convertible to the variable's
type.
 For example, there is no conversion from an

integer to any arbitrary string.


 Therefore, after you declare i as an integer, you

cannot assign the string "Hello" to it, as is shown in


the following code.
int i;
i = "Hello"; // Error: "Cannot implicitly convert type
'string' to 'int'"
Operators in C#
Casting and Type Conversions

 However, you might sometimes need to copy a


value into a variable or method parameter of
another type.

 For example, you might have an integer variable


that you need to pass to a method whose
parameter is typed as double.

 You might need to assign a class variable to a


variable of an interface type.
Operators in C#
Casting and Type Conversions

These kinds of operations are called type


conversions. In C#, you can perform the following
kinds of conversions:

1. Implicit conversions:
2. Explicit conversions (casts):
3. User-defined conversions:
4. Conversions with helper classes:
Operators in C#
Casting and Type Conversions

Implicit Conversions

 For built-in numeric types, an implicit conversion


can be made when the value to be stored can fit
into the variable without being truncated or
rounded off.
 For example, a variable of type long (8 byte integer)
can store any value that an int (4 bytes on a 32-bit
computer) can store.
Operators in C#
Casting and Type Conversions

Implicit Conversions

In the following example, the compiler implicitly


converts the value on the right to a type long before
assigning it to bigNum.

// Implicit conversion. num long can


// hold any value an int can hold, and more!
int num = 2147483647;
long bigNum = num;
Operators in C#
Casting and Type Conversions
Implicit Numeric Conversions Table
From To

sbyte short, int, long, float, double, or decimal

byte short, ushort, int, uint, long, ulong, float, double, or decimal

short int, long, float, double, or decimal

ushort int, uint, long, ulong, float, double, or decimal

int long, float, double, or decimal

uint long, ulong, float, double, or decimal

long float, double, or decimal

char ushort, int, uint, long, ulong, float, double, or decimal

float double

ulong float, double, or decimal


Operators in C#
Casting and Type Conversions
Implicit Numeric Conversions Table

For reference types, an implicit conversion always exists from a


class to any one of its direct or indirect base classes or interfaces.
No special syntax is necessary because a derived class always
contains all the members of a base class.

Derived d = new Derived();


Base b = d; // Always OK.
Operators in C#
Casting and Type Conversions
Explicit Conversions

 However, if a conversion cannot be made without a


risk of losing information, the compiler requires
that you perform an explicit conversion, which is
called a cast.
 A cast is a way of explicitly informing the compiler
that you intend to make the conversion and that
you are aware that data loss might occur.
 To perform a cast, specify the type that you are
casting to in parentheses in front of the value or
variable to be converted.
Operators in C#
Casting and Type Conversions
Explicit Conversions

The following program casts a double to an int. The


program will not compile without the cast.

class Test{
static void Main() {
double x = 1234.7;
int a;
a = (int)x; System.Console.WriteLine(a);
}
}
// Output: 1234
Operators in C#
Casting and Type Conversions
Explicit Numeric Conversions Table
From To
sbyte byte, ushort, uint, ulong, or char
byte Sbyte or char

short sbyte, byte, ushort, uint, ulong, or char

ushort sbyte, byte, short, or char

int sbyte, byte, short, ushort, uint, ulong,or char

uint sbyte, byte, short, ushort, int, or char

long sbyte, byte, short, ushort, int, uint, ulong, or char

ulong sbyte, byte, short, ushort, int, uint, long, or char

char sbyte, byte, or short

float sbyte, byte, short, ushort, int, uint, long, ulong, char,or decimal

double sbyte, byte, short, ushort, int, uint, long, ulong, char, float,or decimal
Operators in C#
Casting and Type Conversions

User-defined conversions:

User-defined conversions are performed by special


methods that you can define to enable explicit and
implicit conversions between custom types that do
not have a base class–derived class relationship.
Operators in C#
Casting and Type Conversions
Conversions with helper classes:

To convert between non-compatible types, such as


integers and System.DateTime objects, or
hexadecimal strings and byte arrays, you can use the
System.BitConverter class, the System.Convert class,
and the Parse methods of the built-in numeric types,
such as Int32.Parse.
Operators in C#
Casting and Type Conversions
Safely Cast by Using as and is Operators
void UseIsOperator(Animal a) {
if (a is Mammal) {
Mammal m = (Mammal)a;
m.Eat(); } }
void UseAsOperator(object o) {
Mammal m = o as Mammal;
if (m != null) {
Console.WriteLine(m.ToString()); }
else {
Console.WriteLine("{0}not a Mammal", o.GetType().Name); } }
Operators in C#
Casting and Type Conversions
Safely Cast by Using as and is Operators
void UseIsOperator(Animal a) {
if (a is Mammal) {
Mammal m = (Mammal)a;
m.Eat(); } }
void UseAsOperator(object o) {
Mammal m = o as Mammal;
if (m != null) {
Console.WriteLine(m.ToString()); }
else {
Console.WriteLine("{0}not a Mammal", o.GetType().Name); } }
Operators in C#
Operator Precedence and Associativity

 When evaluating C# expressions, there are certain


rules to ensure the outcome of the evaluation.
 These rules are governed by precedence and
associativity, and preserve the semantics of all C#
expressions.
 Precedence refers to the order in which operations
should be evaluated. Sub expressions with higher
operator precedence are evaluated first.
 There are two types of associativity: left and right.
 Operators with left associativity are evaluated from
left to right.
 When an operator has right associativity, its
expression is evaluated from right to left.
Operators in C#
Operator Precedence and Associativity

 Certain operators have precedence over others to


guarantee the certainty and integrity of
computations.
 One effective rule of thumb when using most
operators is to remember their algebraic
precedence.

int result;
result = 5 + 3 * 9; // result = 32

To alter the order of operations, use parenthesis,


which have a higher precedence:
result = (5 + 3) * 9; // result = 72
Operators in C#
C# Operator Precedence

Category Operators

Postfix Increment and Decrement ++, --

Prefix Increment, Decrement and Unary ++, --, +, -, !, ~

Multiplicative *, /, %

Additive +, -

Shift <<, >>

Relational <, <=, >, >=

Equality ==, !=

Bitwise AND &

Bitwise XOR ^

Bitwise OR |

Logical AND &&

Logical OR ||

Ternary ?:

Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
C# Keywords
 Keywords are reserved words predefined to
the C# compiler.
 These keywords cannot be used as

identifiers. However, if you want to use these


keywords as identifiers, you may prefix the
keyword with the @ character.
 In C#, some identifiers have special meaning

in context of code, such as get and set are


called contextual keywords.
C# Keywords
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

implici in (generic
foreach goto if in int
t modifier)

interface internal is lock long namespace new

out (generic
null object operator out override params
modifier)
C# Keywords
Reserved Keywords

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 while
C# Keywords
Contextual Keywords

descendi
add alias ascending dynamic from get
ng

partial
global group into join let orderby
(type)

partial
remov
(method select set
e
)
C# Keywords
Contextual Keywords

descendi
add alias ascending dynamic from get
ng

partial
global group into join let orderby
(type)

partial
remov
(method select set
e
)

You might also like