4. What is the C# Programming Language?
C# (pronouncedas“C Sharp”) is a simple,modern,object-oriented,andtype-safeprogramming
language.C#language has itsrootsin C languagessuchas C, C++, and itis mostlysimilartoJava
programming.
C# is a stronglytypedobject-orientedprogramminglanguage.C#isopensource,simple,modern,
flexible,andversatile.Inthisarticle,letuslearnwhatC# is,what C# can do,and how C# is differentfrom
C++ and otherprogramminglanguages.
C# is a programminglanguage of .NetFramework.
C# is pronouncedas"C-Sharp".Itis an object-orientedprogramminglanguage providedbyMicrosoft
that runson .NetFramework.
C# is a programminglanguage developedandlaunchedbyMicrosoftin2001. C# is a simple,modern,
and object-orientedlanguagethatprovidesmoderndaydevelopersflexibilityandfeaturestobuild
software thatwill notonlyworktodaybut will be applicable foryearsinthe future.
A programminglanguage oncomputerscience isalanguage thatis usedto write software programs.
C# Programminglanguage will allowdeveloperstobuildavarietyof secure androbustapplicationssuch
as windowsapplications,webapplications,database applications,etc.,whichwill runon .NET
Framework.
C# programminglanguage hasbeenbuilton.NETFramework torun the C# applications.We are
requiredtoinstall a.NET Framework componentonourmachines.
.NET Framework isa developmentplatformforbuildingappsforwindows,web,azure,etc.,byusing
programminglanguagessuchasC#, F#, and Visual Basic.Itconsistsof two majorcomponents,such
as CommonLanguage Runtime (CLR),anexecutionenginethathandlesrunningapps,and .NET
FrameworkClassLibrary,whichprovidesalibraryof testedandreusable code thatdeveloperscanuse it
intheirapplications.
C# Features
5. C# is object-oriented programming language. It provides many features that are given below.
Simple
Modernprogramminglanguage
Objectoriented
Type safe
Interoperability
Scalable andUpdateable
Componentoriented
Structuredprogramminglanguage
Rich Library
Fast speed
Modernand easy
Fast and opensource
Crossplatform
Safe
Versatile
Simple
C# is a simple language in the sense that it provides structured approach (to break the problem into parts),
rich set of library functions, data types etc.
ModernProgramming Language
C# programming is based upon the current trend and it is very powerful and simple for building scalable,
interoperable and robust applications.
ObjectOriented
C# is object-oriented programming language. OOPs makes development and maintenance easier where as
in Procedure-oriented programming language it is not easy to manage if code grows as project size grow.
Type Safe
C# type safe code can only access the memory location that it has permission to execute. Therefore,it
improves a security of the program.
Interoperability
Interoperability process enables the C# programs to do almost anything that a native C++ application can
do.
Scalable and Updateable
C# is automatic scalable and updateable programming language. For updating our application, we delete
the old files and update them with new ones.
ComponentOriented
C# is component-oriented programming language. It is the predominant software development
methodology used to develop more robust and highly scalable applications.
6. Structured Programming Language
C# is a structured programming language in the sense that we can break the program into parts using
functions. Therefore,it is easy to understand and modify.
Rich Library
C# provides many inbuilt functions that makes the development fast.
Fast Speed
The compilation and execution time of C# language is fast.
C# is modern and easy
C# is a simple,modern,andanobject-orientedprogramminglanguage.The purpose of C#was to
developaprogramminglanguage thatisnotonlyeasyto learnbutalso supportsmodernday
functionalityforall kindof software development.
If you lookat the historyof programminglanguagesandtheirfeatures,eachprogramminglanguage was
designedforaspecificpurpose tosolve aspecificneedatthat time.
C# language howeverwasdesignedtokeepbusinessandenterprisesneedsinmind.C#language was
designedforbusinessestobuildall kindsof softwarebyusingone single programminglanguage.
C# providesfunctionalitytosupportmoderndaysoftware development.C#supportsWeb,Mobile,and
app developmentneeds.Some of the modern-dayprogramminglanguage featuresC#supportsare
generics,vartypes,autoinitializationof typesandcollections,lambdaexpressions,dynamic
programming,asynchronousprogramming,tuples,patternmatching,advanceddebuggingand
exceptionhandling,andmore.
C# language syntaxesare influencedfromC++,Java, Pascal and few otherlanguagesthatare easyto
adopt.C# alsoavoidscomplexityandunstructuredlanguagefeatures.
C# is fast and opensource
C# is opensource underthe .NET Foundation,whichisgovernedandrunindependentlyof Microsoft.C#
language specifications,compilers,andrelatedtoolsare opensource projectsonGitHub.While C#
language feature designisledbyMicrosoft,the opensource communityisveryactive inthe language
developmentandimprovements.
7. C# is fastcompare to several otherhigh-level programminglanguages.C#8 has manyperformance
improvements.
C# is cross platform
C# is cross platformprogramminglanguage.Youcan build.NETapplicationsthatcanbe deployedon
Windows,Linux,andMac platforms.C#apps can alsobe deployedincloudandcontainers.
C# is safe and efficient
C# is a type safe language.C#doesnot allow type conversionsthatmayleadto data lossor other
problems.C#allowsdeveloperstowrite safe code.C#alsofocusesonwritingefficientcode.
Here is a listof some of the keyconceptsinC# that helpswrite safe andefficientcode.
Unsafe type castingisnot allowed.
Null able andnon-null able typesare supportedinC#.
Declare a read-only structtoexpressthata type isimmutable andenablesthe compilertosave copies
whenusinginparameters.
Use a ref read-only returnwhenthe returnvalue isastruct largerthan IntPtr.Size andthe storage
lifetimeisgreaterthanthe methodreturningthe value.
Whenthe size of a read-only structisbiggerthanIntPtr.Size,youshouldpassitas an inparameterfor
performance reasons.
Neverpassa struct as an in parameterunlessitisdeclaredwiththe read-only modifierbecause itmay
negativelyaffectperformance andcouldleadtoan obscure behavior.
Use a ref struct, or a read-only ref structsuch as Span<T> or ReadOnlySpan<T>toworkwithmemoryas
a sequence of bytes.
C# is versatile
C# is a Swissarmyknife.While mostprogramminglanguagesweredesignedforaspecificpurpose,C#
was designedtodoC#. We can use C# to buildtoday’smodernsoftware applications.C#canbe usedto
developall kindof applicationsincludingWindowsclientapps,componentsandlibraries,servicesand
APIs,Webapplications,Mobile apps,cloudapplications,andvideogames.
8. Here is a list of types of applications C# can build:
Windowsclientapplications
Windowslibraries andcomponents
Windowsservices
Webapplications
WebservicesandWebAPI
Native iOSandAndroidmobile apps
Backendservices
Azure cloudapplicationsandservices
Backenddatabase usingML/Data tools
InteroperabilitysoftwaresuchasOffice,SharePoint,SQLServerandsoon.
Artificial IntelligenceandMachine learning
Blockchainsand distributedledgertechnologyincludingcryptocurrency
Internetof Things(IoT) devices
Gamingconsolesandgamingsystems
Videogames
C# History
History of C# language isinterestingtoknow.Here we are goingto discussbrief historyof C#language.
C# is pronouncedas "C-Sharp".Itis an object-orientedprogramminglanguage providedby Microsoft
that runson .Net Framework.Anders Hejlsbergisknownas the founderof C# language.
It isbasedon C++ and Java, but ithas many additional extensionsusedtoperformcomponentoriented
programmingapproach.
C# has evolvedmuchsince theirfirstrelease inthe year 2002. It was introducedwith .NETFramework
1.0 and the current versionof C#is 10.0.
C# Version History
C# was first introduced with .NET Framework 1.0 in the year 2002 and evolved much since
then. The following table lists important features introduced in each version of C#:
9. Version .NET Framework Visual Studio Important Features
C# 1.0 .NET Framework 1.0/1.1 Visual Studio .NET 2002 Basic features
C# 2.0 .NET Framework 2.0 Visual Studio 2005
Generics
Partial types
Anonymous methods
Iterators
Nullable types
Private setters (properties)
Method group conversions (delegates)
Covariance and Contra-variance
Static classes
C# 3.0 .NET Framework 3.03.5 Visual Studio 2008
Implicitly typed local variables
Object and collection initializers
Auto-Implemented properties
Anonymous types
Extension methods
Query expressions
Lambda expressions
Expression trees
Partial Methods
C# 4.0 .NET Framework 4.0 Visual Studio 2010
Dynamic binding (late binding)
Named and optional arguments
Generic co- and contra variance
Embedded interop types
C# 5.0 .NET Framework 4.5 Visual Studio 2012/2013
A sync features
Caller information
10. Version .NET Framework Visual Studio Important Features
C# 6.0 .NET Framework 4.6 Visual Studio 2013/2015
Expression Bodied Methods
Auto-property initializer
name of Expression
Primary constructor
Await in catch block
Exception Filter
String Interpolation
C# 7.0 .NET Core 2.0 Visual Studio 2017
out variables
Tuples
Discards
Pattern Matching
Local functions
Generalized a sync return types
C# 8.0 .NET Core 3.0 Visual Studio 2019
Read-only members
Default interface methods
Using declarations
Static local functions
Disposable ref structs
Nullable reference types
More
C# 9.0 .NET 5.0 Visual Studio 2019
Records
Init-only properties
Top-level statements
Init accessors and readonly fields
With-expressions
Value-based equality
more
11. Version .NET Framework Visual Studio Important Features
C# 10.0 .NET 6.0 Visual Studio 2022
Record structs
Global using directives
File-scoped namespace declaration
Extended Property Patterns
Null Parameter Checking
Constant interpolated strings
more
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
Let us look at a simple code that prints the words "Hello World":
12. 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
Let us look at the various parts of the given program:
• The first line of the program using System;- theusing 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.
• The next 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.
• The Main method specifies its behavior with the statement
Console.WriteLine("Hello World");
13. • 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.
• The last 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.
It is worth to note the following points:
• C# is case sensitive.
• All statements and expression must end with a semicolon (;).
• The program execution starts at the Main method.
• Unlike Java, program file name could be different from the class name.
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.
• Choose Console Application.
14. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
• 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.
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.
C# is an object-oriented programming language. In Object-Oriented Programming
methodology, a program consists of various objects that interact with each other by means of
actions. The actions that an object may take are called methods. Objects of the same kind are
said to have the same type or are said to be in the same class.
For example, let us consider a Rectangle object. It has attributes such as length and width.
Depending upon the design, it may need ways for accepting the values of these attributes,
calculating the area, and displaying details.
Let us look at implementation of a Rectangle class and discuss C# basic syntax:
using System; namespace
RectangleApplication
{ class
Rectangle
{
// member variables
double length; double
width; public void
Acceptdetails()
{
length = 4.5;
15. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
width = 3.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());
}
} class
ExecuteRectangle
{ static void Main(string[]
args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 3.5
Area: 15.75
16. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
The using Keyword
The first statement in any C# program is
using System;
The using keyword is used for including the namespaces in the program. A program can
include multiple using statements.
The class Keyword
The class keyword is used for declaring a class.
Comments in C#
Comments are used for explaining code. Compilers ignore the comment entries. The multiline
comments in C# programs start with /* and terminates with the characters */ as shown below:
/* This program demonstrates
The basic syntax of C# programming
Language */
Single-line comments are indicated by the '//' symbol. For example,
}//end class Rectangle
Member Variables
Variables are attributes or data members of a class, used for storing data. In the preceding
program, the Rectangle class has two member variables named length and
width.
Member Functions
Functions are set of statements that perform a specific task. The member functions of a class
are declared within the class. Our sample class Rectangle contains three member functions:
AcceptDetails, GetArea and Display.
Instantiating a Class
In the preceding program, the class ExecuteRectangle contains the Main() method and
instantiates the Rectangle class.
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user defined
item. The basic rules for naming classes in C# are as follows:
• A name must begin with a letter that could be followed by a sequence of letters,
digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
• It must not contain any embedded space or symbol such as ? - +! @ # % ^ & *
( ) [ ] { } . ; : " ' / and . However, an underscore ( _ ) can be used.
17. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
• It should not be a C# keyword.
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.
The following table lists the reserved keywords and contextual keywords in C#:
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 while
Contextual Keywords
add alias ascending descending dynamic from get
18. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
global group into join let orderby
partial
(type)
partial
(method)
remove select set
C# Arithmetic Operators
In c#, Arithmetic Operators are useful to perform basic arithmetic calculations like addition, subtraction,division, etc., based on
our requirements.
For example, we have integer variables x = 20, y = 10, and if we apply an arithmetic operator + (x + y) to perform an addition
operator. We will get the result as 30 like as shown below.
int result;
int x = 20, y = 10;
result = (x + y);
The following table lists the different types of operators available in c# arithmetic operators.
Operator Name Description Example (a = 6, b = 3)
+ Addition It adds two operands. a + b = 9
- Subtraction It subtracts two operands. a - b = 3
* Multiplication It multiplies two operands. a * b = 18
/ Division It divides numerator by de-numerator. a / b = 2
% Modulo It returns a remainder as a result. a % b = 0
C# Arithmetic Operators Example
Following is the example of using the Arithmetic Operators in the c# programming language.
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int result;
int x = 20, y = 10;
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);
result = (x * y);
19. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
Console.WriteLine("Multiplication Operator: "+ result);
result = (x / y);
Console.WriteLine("Division Operator: " + result);
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above code, we used Arithmetic operators (+, -, *, /, %) to perform different operations on defined operands
based on our requirements.
Output of C# Arithmetic Operators Example
When we execute the above c# program, we will get the result as shown below.
This is how we can use arithmetic operators in the c# programming language to perform the basic arithmetic calculations on
operands based on our requirements.
C# Relational Operators
In c#, Relational Operators are useful to check the relation between two operands as we can determine whether two operand
values equal or not, etc., based on our requirements.
Generally, the c# relational operators will return true only when the defined operands relationship becomes true. Otherwise, it will
return false.
For example, we have integer variables a = 10, b = 20. If we apply a relational operator >= (a >= b), we will get the
result false because the variable “a” contains a value that is less than variable b.
The following table lists the different types of operators available in c# relational operators.
Operator Name Description
Example (a = 6,
b = 3)
== Equal to It compares two operands,and it returns true if both are the same. a == b (false)
> Greater than It compares whether the left operand greater than the right operand or not
and returns true if it is satisfied.
a > b (true)
20. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
Operator Name Description
Example (a = 6,
b = 3)
< Less than It compares whether the left operand less than the right operand or not and
returns true if it is satisfied.
a < b (false)
>= Greater than or
Equal to
It compares whether the left operand greater than or equal to the right
operand or not and returns true if it is satisfied.
a >= b (true)
<= Less than or
Equal to
It compares whether the left operand less than or equal to the right operand
or not and returns true if it is satisfied.
a <= b (false)
!= Not Equal to It checks whether two operand values equal or not and return true if values
are not equal.
a != b (true)
C# Relational Operators Example
Following is the example of using the Relational Operators in c# programming language.
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
bool result;
int x = 10, y = 20;
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
result = (x > y);
Console.WriteLine("Greater than Operator: " + result);
result = (x <= y);
Console.WriteLine("Lesser than or Equal to: "+ result);
result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above code, we used different Relational operators (<, >, ==) to perform required operations on defined
operands.
Output of C# Relational Operators Example
When we execute the above c# program, we will get the result as shown below.
21. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
This is how we can use the relational operators in the c# programming language to check the relationship between defined operands
based on our requirements.
C# Logical Operators
In c#, Logical Operators are useful to perform the logical operation between two operands like AND, OR, and NOT based on our
requirements. The Logical Operators will always work with Boolean expressions (true or false) and return Boolean values.
The operands in logical operators must always contain only Boolean values. Otherwise, Logical Operators will throw an error.
The following table lists the different types of operators available in c# logical operators.
Operator Name Description
Example (a = true, b =
false)
&& Logical
AND
It returns true if both operands are non-zero. a && b (false)
|| Logical OR It returns true if any one operand becomes a non-zero. a || b (true)
! Logical
NOT
It will return the reverse of a logical state that means if both operands are
non-zero, it will return false.
!(a && b) (true)
If we use Logical AND, OR operators in c# applications, those will return the result as shown below for different inputs.
Operand1 Operand2 AND OR
true true true true
true false false true
false true false true
false false false false
22. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
If you observe the above table, if any one operand value becomes false, then the logical AND operator will return false.
The logical OR operatorwill return true if any one operand value becomes true.
If we use the Logical NOT operator in our c# applications, it will return the results like as shown below for different inputs.
Operand NOT
true false
false true
If you observe the above table, the Logical NOT operator will always return the reverse value of the operand. If the operand value
is true, then the Logical NOT operator will return false and vice versa.
C# Logical Operators Example
Following is the example of using the Logical Operators in c# programming language.
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 15, y = 10;
bool a = true, result;
// AND operator
result = (x <= y) && (x > 10);
Console.WriteLine("AND Operator: " + result);
// OR operator
result = (x >= y) || (x < 5);
Console.WriteLine("OR Operator: " + result);
//NOT operator
result = !a;
Console.WriteLine("NOT Operator: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above code, we used logical operators (AND, OR, NOT) to perform different operations on defined operands.
Output of C# Logical Operators Example
When we execute the above c# program, we will get the result as shown below.
23. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
This is how we can use logical operators in the c# programming language to perform logical operations on defined operands bas ed
on our requirements.
C# Bitwise Operators
In c#, Bitwise Operators will work on bits, and these are useful to perform bit-by-bit operations such as Bitwise AND (&), Bitwise
OR (|), Bitwise Exclusive OR (^), etc. on operands.We can perform bit-level operations on Boolean and integer data.
For example, we have integer variables a = 10, b = 20, and the binary format of these variables will be shown below.
a = 10 (00001010)
b = 20 (00010100)
When we apply the Bitwise OR (|) operator on these parameters, we will get the result shown below.
00001010
00010100
-----------
00011110 = 30 (Decimal)
The following table lists the different types of operators available in c# bitwise operators.
Operator Name Description
Example (a =
0, b = 1)
& Bitwise AND It compares each bit of the first operand with the corresponding bit of its
second operand.If both bits are 1, then the result bit will be 1; otherwise, the
result will be 0.
a & b (0)
| Bitwise OR It compares each bit of the first operand with the corresponding bit of its
second operand.If either of the bit is 1, then the result bit will be 1; otherwise,
the result will be 0.
a | b (1)
^ Bitwise Exclusive
OR (XOR)
It compares each bit of the first operand with the corresponding bit of its
second operand.If one bit is 0 and the otherbit is 1, then the result bit will be
1; otherwise, the result will be 0.
a ^ b (1)
~ Bitwise
Complement
It operates on only one operand,and it will invert each bit of operand.It will
change bit 1 to 0 and vice versa.
~(a) (1)
<< Bitwise Left Shift) It shifts the number to the left based on the specified number of bits. The
zeroes will be added to the least significant bits.
b << 2 (100)
24. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
Operator Name Description
Example (a =
0, b = 1)
>> Bitwise Right Shift It shifts the number to the right based on the specified number of bits. The
zeroes will be added to the least significant bits.
b >> 2 (001)
C# Bitwise Operators Example
Following is the example of using the Bitwise Operators in the c# programming language.
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 5, y = 10, result;
result = x & y;
Console.WriteLine("Bitwise AND: " + result);
result = x | y;
Console.WriteLine("Bitwise OR: " + result);
result = x ^ y;
Console.WriteLine("Bitwise XOR: " + result);
result = ~x;
Console.WriteLine("Bitwise Complement: " + result);
result = x << 2;
Console.WriteLine("Bitwise Left Shift: " + result);
result = x >> 2;
Console.WriteLine("Bitwise Right Shift: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above code, we used different bitwise operators (&, |, ^, ~, <<, >>) to perform different operations on defined
operands.
Output of C# Bitwise Operators Example
When we execute the above c# program, we will get the result as shown below.
25. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
This is how we can use bitwise operators in the c# programming language to perform bit-by-bit operations on defined operands
based on our requirements.
C# Assignment Operators
In c#, Assignment Operators are useful to assign a new value to the operand, and these operators will work with only one operand.
For example, we can declare and assign a value to the variable using the assignment operator (=) like as shown below.
int a;
a = 10;
If you observe the above sample, we defined a variable called “a” and assigned a new value using an assignment operator (=) based
on our requirements.
The following table lists the different types of operators available in c# assignment operators.
Operator Name Description Example
= Equal to It is used to assign the values to variables. int a; a = 10
+= Addition Assignment It performs the addition of left and right operands and assigns a
result to the left operand.
a += 10 is equals to
a = a + 10
-= Subtraction Assignment It performs the subtraction of left and right operands and assigns a
result to the left operand.
a -= 10 is equals to a
= a - 10
*= Multiplication
Assignment
It performs the multiplication of left and right operands and
assigns a result to the left operand.
a *= 10 is equals to
a = a * 10
/= Division Assignment It performs the division of left and right operands and assigns a
result to the left operand.
a /= 10 is equals to a
= a / 10
%= Modulo Assignment It performs the modulo operation on two operands and assigns a
result to the left operand.
a %= 10 is equals to
a = a % 10
&= Bitwise AND
Assignment
It performs the Bitwise AND operation on two operands and
assigns a result to the left operand.
a &= 10 is equals to
a = a & 10
|= Bitwise OR Assignment It performs the Bitwise OR operation on two operands and
assigns a result to the left operand.
a |= 10 is equals to a
= a | 10
^= Bitwise Exclusive OR
Assignment
It performs the Bitwise XOR operation on two operands and
assigns a result to the left operand.
a ^= 10 is equals to
a = a ^ 10
26. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
Operator Name Description Example
>>= Right Shift Assignment It moves the left operand bit values to the right based on the
number of positions specified by the second operand.
a >>= 2 is equals to
a = a >> 2
<<= Left Shift Assignment It moves the left operand bit values to the left based on the
number of positions specified by the second operand.
a <<= 2 is equals to
a = a << 2
C# Assignment Operators Example
Following is the example of using assignment Operators in the c# programming language.
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 20;
x += 10;
Console.WriteLine("Add Assignment: " + x);
x *= 4;
Console.WriteLine("Multiply Assignment: " + x);
x %= 7;
Console.WriteLine("Modulo Assignment: " + x);
x &= 10;
Console.WriteLine("Bitwise And Assignment: " + x);
x ^= 12;
Console.WriteLine("Bitwise XOR Assignment: " + x);
x >>= 3;
Console.WriteLine("Right Shift Assignment:" + x);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above example, we defined a variable or operand “x” and assigning new values to that variable by using
assignment operators in the c# programming language.
Output of C# Assignment Operators Example
When we execute the above c# program, we will get the result as shown below.
27. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
This is how we can use assignment operators in c# to assign new values to the variable based on our requirements.
C# Operators Precedence
In c#, Operators Precedence is useful to define multiple operators in a single expression, and the evaluation of expression can be
happened based on the priority of operators.
For example, the multiplication operator(*) is having higher precedence than the addition operator (+). So if we use both
multiplication (*) and addition (+) operators in a single expression, first, it will evaluate the multiplication part and then the addition
part in expression.
Following is the simple example of defining an expression with operator precedence in c#.
int i = 3 + 4 * 5;
When we execute the above statement, the multiplication part (4 * 5) will be evaluated first. After that,the addition part (3 + 12)
will be executed, and the i value will become a 23.
As said earlier, the multiplication (*) operator is having higher precedence than the addition (+) operatorso that the first
multiplication part will be executed.
The following table lists the different types of operators available in c# relational operators.
Category Operator(s)
Postfix / Prefix ++, --
Unary +, -, !, ~
Multiplicative *, /, %
Additive +, -
Shift <<, >>
Relational <, <=, >, >=
Equality ==, !=
28. Departmentof InformationTechnology Event-DrivenProgrammingC#
ETHIOPIAN POLICEUNIVERSITY
Category Operator(s)
Bitwise &, |, ^
Logical &&, ||
Conditional ?:
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
C# Operator Precedence Example
Following is the example of implementing operator precedence in the c# programming language.
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 20, y = 5, z = 4;
int result = x / y + z;
Console.WriteLine("Result1: "+result);
bool result2 = z <= y + x;
Console.WriteLine("Result2: "+result2);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above example, we implemented operator precedence with multiple operators.The evaluation of expressions will
be done based on operators'priority in the c# programming language.
Output of C# Operators Precedence Example
When we execute the above c# program, we will get the result as shown below.
This is how we can implement operatorprecedence in the c# programming language based on our requirements.