0% found this document useful (0 votes)
88 views43 pages

TOPPERS NOTES II IT

this is a study material

Uploaded by

Kalaiyarasi.p
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views43 pages

TOPPERS NOTES II IT

this is a study material

Uploaded by

Kalaiyarasi.p
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

TOPPERS NOTES

UNIT - I
.NET:
 .NET stands for Network Enable Technology which is developed by Microsoft Corporation.
 .NET is a collection of languages like VC#.NET, VC++.NET, VB.NET and so on.
 .NET is a Framework which provides a common platform to Execute or Run the applications
developed in various programming languages.
.NET Objectives: The .NET Framework is designed to fulfil the following objectives
 Platform independent: As .exe and .dll files work in any operating system with the help of
CLR, hence .Net is called as platform independent.
 (.exe) is executable file, it consists of executable code, and (.dll) is dynamic link library file it
consist of reusable code. .exe and .dll files contains the code in the format of byte code is also
called as MSIL (Microsoft intermediate language) code.
 Machine language is also called as native code. CLR is common language runtime; CLR
software converts byte code into native code. Dot Net is platform independent but CLR
software is platform dependent.
One question arises if we go in detail, that is either Dot Net is pure platform independent or
not? Answer is Dot Net is partially platform dependent, as of now CLR software's are not
available for DOS operating system and Windows 95.

 Language independent: As Dot Net programming logic can be developed in any Dot Net
framework compatible languages; hence Dot Net is called as language independent.
Microsoft is introducing approximately 40 languages into Dot Net framework, out of which as
of now approximately 24 languages and one specification are released. Ex:
VC#.Net,VB.Net,VC++,VJ#,VF#,PHP,COBOL,PERL,PHYTHON,SMALLTALK,JSCRI
PT...etc One specification is ASP.Net.
 Language interoperability: It is a concept of developing an application with the help of
more than one .NET programming language. After an application is compiled, the source
code will be converted into byte code. Byte code follows a standard instruction set provided
by cls(common language specification).Cls provides common rules and syntaxes for all the
languages and cls also provides common data types for all the languages and these common
data types are called as CTS(common type system).
C++ C# VB .NET
int(2) short(2) short(2)
long(4) int(4) integer(2)
long(8) long(8)
SYSTEM.INT16
SYSTEM.INT32
SYSTEM.INT64
 It supports object-oriented programming environment.
 It supports to work with database programming with the help of ADO.NET.
 It supports to work with WPF (windows presentation foundation) for developing animations.
 It Provides environment for developing various types of applications, such as Windows-
based applications and Web-based applications
 It Supports to develop 3-tier architecture with the help of Dot Net remoting
 Supports to develop game programming with the help of multi-threading
 Supports to work with link programming
Managed Code: The code is developed and running under the control of the CLR is often termed
managed code
Unmanaged code: The code which takes OS help while execution is called as unmanaged code
Note: Managed code is faster in execution.
Unmanaged code

CLR
.net .dll
.exe Output

Managed code
 The .Net framework is a revolutionary platform that helps you to write the following types of
applications:
Windows applications

The .NET framework applications are multi-platform applications.


 The .NET framework has been designed in such a way that it can be used by .NET
framework compatible languages ( C#, C++, Visual Basic, Jscript, COBOL, etc). All .NET
framework compatible languages can access the framework as well as communicate with
each other.
 The .NET frame work contain three major things that is
 Languages—VB,C#,PASCAL,COBOL
 Technology—ASP.NET,ADO.NET
 Servers—SQL SERVER,SHARE POINT SERVER
 In platform independent languages, the code gets executed under the control of special
software called framework.
Example: java-->JVM
.NET-->CLR
 Framework: A framework is a software which masks the functionalities of a OS and makes
the code to execute under its control .Frame work provides the following basic features like
 Platform independency
 Security
 Memory management
 Microsoft has started the development of .NET framework in late 90‘s originally under the
name of NGWS (next generation windows services).
 To develop the framework first the Microsoft has prepared a set of specifications known as
CLI (common language infrastructure).
 The .NET specifications are open to all (everyone can develop) which is standardized under
ISO (International Standards organization) AND ECMA(European computer manufacture
association).
 CLI specification talks about four important aspects that is
CLS (common language specification)
CTS (common Type system)
BCL (Base class libraries)
VES (Virtual execution system) or CLR (common language runtime)
 .NET framework versions
Versions Release Date

1.0 2002
1.1 2003
2.0 2005
3.0 2006
3.5 2007
4.0 2009
 The .Net framework consists of an enormous library of codes used by the client languages
such as C#. Following are some of the components of the .Net framework:
 Common Language Runtime (CLR)
 The .Net Framework Class Library
 Common Language Specification
 Common Type System
 Metadata and Assemblies
 Windows Forms
 ASP.Net and ASP.Net AJAX
 ADO.Net
 Windows Workflow Foundation (WF)
 Windows Presentation Foundation
 Windows Communication Foundation (WCF)
 LINQ
.NET framework architectural diagram: The .NET framework is one of the tool provided by
the .NET infrastructure and tools component of the .NET platform. The .NET framework provides an
environment for building, deploying and running web services and .NET applications.

PLINQ TPL
LINQ ADO.NET ENTITY FRAMEWORK
WPF WCF WF CARD SPACE
ADO.NET ASP.NET WIN FORMS
BASE CLASS LIBRARIES

COMMON LANGUAGE RUNTIME(CLR)


Common language runtime (CLR):
 CLR is the heart of the .NET framework. It is the execution engine of .NET framework,
where all .net applications are running under the supervision of CLR. The main function of
CLR is to convert the managed code into native code and then execute the program. CLR acts
as a layer between OS and the applications written in .NET languages. CLR provides various features
to applications like
 Security
 Platform independency
 Automatic memory management
 Runtime error handling
 Code verification
 Compilation
 Thread management
 The components of CLR are
Class Loader: It is used to load all the classes at runtime for the execution of an application. JIT
Compiler: It is responsible for the conversion of MSIL (byte code) into machine code
(native code).
Code Manager: Is responsible for managing code at runtime.
Garbage Collector: The .NET garbage collector is responsible for automatic memory
management, where memory management is a process of allocation and de-allocation of
memory that is required for a program execution. Memory management is of two types
1. Manual/explicit memory management: In this the programmers are responsible
for allocation and deallocation of memory that is required for a program execution.
2. Automatic/implicit memory management: In this case the garbage collector will
take care of allocation and deallocation process of memory.
The garbage collector will allocates the memory for an object when and where they are required
and also deallocates the memory of those objects once they become unused under the
program. The unused object of a program is called garbage and deallocate immediately.
Security Engine (manager): It is responsible for taking care of the security of the
application that is security engine will not allow the application to interact directly with the
operating system (or) OS to interact with the application.
Type Checker: It enforces strictness in type checking that is type checker will verify the
types used in the application with CTS (or) CLS standards supported by the CLR.
Common type system: Common Type System (CTS) describes a set of types that can be used in
different .Net languages in common. That is, the Common Type System (CTS) ensure that
objects written in different .Net languages can interact with each other.
Microsoft Intermediate Language (MSIL): MSIL stands for Microsoft Intermediate
Language. We can call it as Intermediate Language (IL) or Common Intermediate Language
(CIL). During the compile time, the compiler convert the source code into Microsoft
Intermediate Language (MSIL) .Microsoft Intermediate Language (MSIL) is a CPU-
independent set of instructions that can be efficiently converted to the native code. During the
runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the
Microsoft Intermediate Language (MSIL) code into native code to the Operating System.

Thread Support: It allows multithreading support to our application.


Debug engine: It allows proper debugging of an application.
Base class library: It provides all the types that an application need at runtime.
Exception manager: Handles all the exception for an application during runtime.
COM Marshaller: It provides interoperability to our applications.
 Base class libraries:
 A library is a set of reusable functionalities where each and every programming language has
built in library like header files in c/c++ ,packages in java similarly .NET languages have
built in libraries known as base class libraries .the speciality of these library is that they can
be consumed under any .NET language(BCL are the best example of language
interoperability because those library are developed in C# language and can be consumed in
any .NET framework compatible languages.
 The very popular namespace in base class library is system
 We can use the base class library in system namespace for many different tasks including.
 Input/output operations
 String handling
 Managing arrays, lists and maps
 Accessing files and file systems
 Security
 Windowing
 Windows messages
 Drawing
 Database management
 Managing errors and exceptions
 Win form technology is used to develop windows based applications.
 Asp.net is used to build rich internet based web applications
 Ado.net is used to create Data Access Layer to query and manipulate data from underlying data
source like SQL Server, Oracle etc.
 WPF (windows presentation foundation) is used to create applications with a rich user
experience. It includes application User Interface, 2D graphics, 3D graphics and multimedia. It
takes advantage of hardware acceleration of modern graphic cards. WPF makes the User
Interface faster, scalable and resolution independent.
 WCF (windows communication foundation) is used for building and developing services
based on Web Services standards.
 WF (WWF) stands windows workflow foundation, which is used to build process oriented
business workflow and rules engine.
 LINQ (language integrated query) allows you to query(communicate) the data from the
various data sources (like SQL databases, XML documents, Ado.Net Datasets, Various Web
services and any other objects such as Collections, Generics etc.) using a SQL Query like syntax
with .Net framework languages like C# and VB.
 ADO.NET Entity Framework provides added features under the traditional ADO.NET. This is
used to query and store data into to the relational databases (like SQL Server, Oracle, DB2 etc.)
in ORM (Object-relational mapping) fashion.
 TPL (Task Parallel Library): The purpose of TPL is to make the developers more productive
by simplifying the process of adding parallelism and concurrency to applications.
 PLINQ (Parallel Language Integrated Query): It is used to maximize processor utilization
with increased throughput in a multicore architecture.
The Origins of .NET Technology: The Origins of the .NET Technology are
 OLE Technology (Object Linking and Embedding): Object linking and embedding (OLE)
was developed by Microsoft in the early 1990‘s to enable inter process communication.OLE
provides support to achieve the following.
 To embed documents from one application into another application.
 To enable one application to manipulate objects located in other application.
OLE Technology enabled uses to develop applications which required interoperability between
various modules such as MS-Word and MS-Excel
 COM Technology (Component Object Model): Till the advent of com technology, the
monolithic approach had been used for developing software. But when the programs became
too large and complex, the monolithic approach leads to a number of problems in terms of
maintainability and testing of software. To overcome these problems Microsoft introduced a
component based model for developing software. In this approach a program is divided into
number of independent components where each one offers a particular task. Each Component
can be developed and tested independently and then integrated into the main system. This
technology is called component object model (COM).
Benefits:
1. It reduces the complexity of software.
2. It enhances software maintainability
3. It enables distributed development among multiple departments (or) organizations.
 .NET Technology (Network Enable Technology):
1. It is a third-generation component model which provides a new level of interoperability
Compared to COM technology.
2. It Enables Application level communication by Microsoft intermediate language(MSIL
or CIL) mechanism.
3. .NET Technology allows true cross-language integration with MSIL.
4. .NET Technology contains MSIL and also includes other technologies and tools
that enable users to develop and implement applications easily.
.NET Languages: The .NET framework is a language neutral. So we can use the number of
languages for developing .NET applications. They include
Native to .NET:
 C#
 Visual basic
 C++
 Jscript
Third-Party languages:
 COBOL
 Eiffel
 Perl
 Python
 Small Talk
 Mercury
 Scheme
All .NET languages are not created equal. Some can use the components of other languages,
some can use the classes produced in other languages to create objects, and some languages can
extend the classes of other languages using the inheritance features of .NET.
Benefits of the .NET Framework
 Simple and faster system development
 Enhanced built in functionality.
 It supports rich oop concepts
 Integration of different applications into one platform.
 Ease of deployment and execution
 Interoperability with existing applications.
 Wide range of scalability
 Simple and easy to build sophisticated development tools.
 Fewer bugs
 Potentially better performance.
Features of .NET:
 Language independency
 Base class library‘s
 Portability
 COM interoperability
 CLR
 Memory management
 Simplified development
Integrated Development Environment (IDE) for C#: An IDE is a tool that helps you write your programs
Microsoft provides the following development tools for C# programming:
 Visual Studio 2010 (VS)
 Visual C# 2010 Express (VCE)
 Visual Web Developer
The last two are freely available from Microsoft official website. Using these tools, you can
write all kinds of C# programs from simple command-line applications to more complex
applications. You can also write C# source code files using a basic text editor like Notepad, and
compile the code into assemblies using the command-line compiler, which is again a part of
the .NET Framework.
of Visual Studio and has the same appearance. They retain most features of Visual Studio.
INTRODUCING C# (PRONOUNCED "C SHARP"): C# is a simple, modern, general-purpose,
object-oriented and type-safe programming language developed by Microsoft, USA and approved by
European Computer Manufacturers Association (ECMA) and International Standards Organization
(ISO).
C# was developed by Anders Hejlsberg and his team during the development of .Net
Framework. C# is designed for Common Language Infrastructure (CLI), which consists of the
executable code and runtime environment that allows use of various high-level languages on
different computer platforms and architectures.
C# can be used to create various types of applications, such as web, windows, console
applications or other types of applications using Visual studio.
HISTORY OF C# LANGUAGE: During the development of .NET, the class libraries were
originally written in a language called simple managed code (SMC) and later the language had been
renamed as C#.
The C# principal designer and lead architect Anders Hejlsberg has previously involved with
the design of visual j++, Borland Delphi, Turbo Pascal languages.
The following reasons make C# a widely used professional language:
 It is a modern, general-purpose programming language
 It is object oriented.
 It is component oriented.
 It is easy to learn.
 It is a structured language.
 It produces efficient programs.
 It can be compiled on a variety of computer platforms.
 It is a part of .Net Framework.
OVERVIEW OF C#: C# can be used to develop two categories of programs, that is
 Executable application programs: These programs are written to carry out certain tasks and
require the main method in one of the classes.
 Component libraries: These do not require a main declaration because they are not stand-
alone application programs. These are written for use by other applications.
CHARACTERISTICS OF C#:
SIMPLE:
1. C# is simple by eliminating some operators such as "::‖ or "->" and pointers.
2. C# treats integer and Boolean data types as entirely two different data types. Boolean values
are pure true or false values in C# so no more errors of "="operator and "=="operator."==" is
used for comparison operation and "=" is used for assignment operation.
MODERN: C# is a modern language because of the following features.
1. It provides Automatic garbage collection.
2. It provides Rich intrinsic model for error handling.
3. It provides Modern approach to debugging
4. It provides robust security model.
5. It provides Decimal data type for financial applications.
OBJECT ORIENTED:
1. C# truly object oriented. It supports Data Encapsulation, inheritance, polymorphism,
interfaces.
2. In C#, everything is an object .there are no more global functions, variables and constants.
TYPE SAFE:
1. In C# we cannot perform unsafe casts like convert double to a Boolean.
2. All dynamically allocated objects and arrays are initialized to zero.
3. Usage of any uninitialized variable produces an error message by the compiler.
4. Access to Arrays is range checked and warned if it goes out of boundary.
5. C# checks the Overflow in arithmetic operations.
6. C# supports automatic garbage collection
INTEROPERABILITY: C# provides support for using COM objects, No matter what language was
used to develop them. C# also supports a special feature that enables a program to call out any native
API.
CONSISTANT: C# supports an unified system, which eliminates the problem of varying integer types.
All types are treated as objects and developers can extend the type system simply and easily.
VERSIONABLE: Making new versions of software modules work with the existing applications is
known as versioning with the help of new and override keywords, With this support, a programmer
can guarantee that his new class library will maintain binary compatibility with the existing client
application.
COMPATIBLE: C# enforces the .NET CLS (common language specification) and therefore allows
interoperation with other .NET language. C# provides support for transparent access to COM and
OLE Applications.
Applications of C#:
 Console applications
 Windows applications
 Developing windows controls
 Developing ASP.NET projects
 Creating web controls
 Providing web services
 Developing .NET component library
NOTES:
 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.
CREATING A SIMPLE C# PROGRAM: A simple code that prints the words "Hello World":
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
Output: Hello World
using System:
using System:
 using is the keyword, which is used to specify namespace.
 The above line tells the compiler to look into the System namespace library for unresolved
class names.
 Because of the above line we have not used system prefix to the console class in the output
line.
 When the compiler parses the Console.WriteLine method, it will understand that the method
is undefined, However it will search through the namespaces specified in using directives and
upon finding the method in the system namespace ,will compile the code without any
Namespace declaration: A namespace is a collection of classes. The HelloWorldApplication
namespace contains the class Hello World.
Class Declaration: 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 behaviour of the class. However, the HelloWorld class has only one method Main. The
line
class Helloworld:
 The above line Declares a class, C# is true object oriented language and therefore everything
must be placed inside a class.
 Class is keyword, which declares new class definition.
 Helloworld is the name of the class. It should be a valid identifier.
Braces({ }):C# is a block structured language and the code always enclosed by { and }.therefore every
class definition in c# begins with opening brace { and ends with a closing brace }.
Public static void Main(): The line
public static void Main()
 The above line defines a method named Main. Every C# executable program must include
the Main() method in one of the classes. This is the starting point for executing the program.
A C# application can have any number of classes but only one class can have the Main()
method to initiate the execution.
 The above line contains public, static and void keywords
public: It tells the C# compiler that Main() method is accessible by anyone.
static: The keyword static declares the Main() method is a global one and can be called without
creating an instance of the class.
void: The keyword void is a type modifier that tells that the main method does not return any value.
 In contrast to other languages main has capital, not lower case M.
Output line: System.Console.WriteLine(“hi”);
 The WriteLine is the static method of the Console class, Which is located in system
namespace.
 . is represented as the member access operator.
 ; is called line terminator
 WriteLine always append a newline character to the end of the string. This means any
subsequent output will start on a newline
COMMENTS: Comments play very important role in the maintenance of programs.They are used to
enhance readability and understanding of code. C# supports two types of comments
 Single line comments: Single line comments begins with a double backslash (//)symbol and
terminate at the end of the line.
Example: //c# program
 Multiline comments: If we want to use multiple lines for a comment, This comment starts
with /* and terminates with */.
Example: /* this is Example of c#
Csharp program */
Console.ReadKey (); The line Console.ReadKey (), 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.
COMPILING AND EXECUTING THE PROGRAM: If you are using Visual Studio.Net for
compiling and executing C# programs, take the following steps:
o Start Visual Studio.
o On the menu bar, choose File -> New -> Project.
o Choose Visual C# from templates, and then choose Windows.
o Choose Console Application.
o Specify a name for your project and click OK button. This creates a new project in Solution
Explorer.
o Write code in the Code Editor.
o 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.
Example: 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;
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();
}
}
}
Output: Length: 4.5 Width: 3.5 Area: 15.75
USING ALIASES FOR NAMESPACE CLASSES: we have seen how we can avoid the prefix
System to the Console class by implementing the using System; statement. can use this approach to
avoid prefixing of System.Console to the method WriteLine() ? The answer is no.
System is a namespace and Console is a class. The using directive can be applied only to
the namespaces and cannot be applied to classes. Therefore the statement
using System.Console;
The above statement is illegal. However, we can overcome this problem by using aliases for
namespace classes. This takes the following form.
using aliasname=classname;
Example: using A= System.Console; //A is alias for
System.Console class sample
{
pubic static void Main()
{
A.WriteLine(―Hello‖);
}
}
PASSING STRING OBJECTS TO WRITELINE METHOD: So far we have seen constant string
output to the Console. we can store string values in string objects and use these objects as parameters
to the WriteLine method. We can use string data type to create string variable and assign string
constant to it.
string s=”abc”;
The content of s may be printed out using the WriteLine method.
System.Console.WriteLine(s);
Example: using System;
class sample
{
class static void Main()
{
string name=‖c sharp‖;
Console.WriteLine(name);
}
}
COMMAND LINE ARGUMENTS: command line arguments are parameters supplied to the Main
method at the time of invoking it for execution.
Example: using System;
class sample
{
public static void Main(string[] args)
{
Console.Write(―welcome to‖);
Console.Write(― ‖+arg[0]);
Console.WriteLine(― ‖+args[1]);
}
}
In this program the Main is declared with a parameter args.The parameter args is declared as an array
of strings(known as string objects).Any arguments provided in the command line(at the time of
execution) are passed to the array aegs as its elements.We can access the array elements by using a
subscript like args[0],args[1] and so on.
For example , consider the command line => Sample c sharp
This command line contains two arguments which are assigned to the array args as follows
C  args[0]
Sharp  args[1]
If we execute the program with the above command line, we will get the following
output Output: welcome to c sharp
WriteLine(): Outputs one (or) more values to the screen but adds a newline character at the end of
the output.
Example: Console.WriteLine(―hello‖);
Console.WriteLine(―c sharp‖);
Output: hello
C sharp
Write():Outputs one (or) more values to the screen without a newline character.
Example: Console.Write(―hello‖);
Console.Write(―\n‖);
Console.Write(― c
sharp‖);
Output: hello
C sharp
MAIN WITH A CLASS:
Example: class testclass
{
public void fun()
{
System.Console.WriteLine(―C# is simple‖);
}
}
class sample
{
public static void Main()
{
testclass test= new testclass(); // creating test object
test.fun(); // calling fun() function
}
}
 The above program has two class declarations, one for the testclass and another for the Main
method.testclass contains only one method to print a string ―C# is simple‖.The Main method
in simple class creates an object of testclass and uses it to invoke the method fun() contained
in testclass.
 The object test is used to invoke the method fun() of testclass with the help of the dot
operator.
PROVIDING INTERACTIVE INPUT: So far we have seen two approaches for giving values to
string objects.
 Using an assignment statement.
 Through command line arguments.
It is possible to give values to string variables interactively through the keyboard at the time of
execution.

Example: using System;


class sample
{
public static void Main()
{
Console.WriteLine(―enter your name‖); string
name=Console.ReadLine();
Console.WriteLine(―Hello‖+name);
}
}
The method ―Console.WriteLine(“enter your name”);‖ outputs the message ―enter your name‖ and
the method ―Console.ReadLine();‖ causes the the execution to wait for the user to enter his name.
The moment the user types his name and presses the enter key, the input is read into the string
variable name. The second output line ―Console.WriteLine(“Hello”+name);‖ concatenates the
name-string with hello and presents the resultant string to the user.
Output: enter your name raja
Hello raja
Example1: using System;
class sample
{
public static void Main()
{
Console.WriteLine(―what is your name‖);
string s=Console.ReadLine();
Console.WriteLine(―Hello‖+s);
Console.WriteLine(―what is your age‖);
string s=Console.ReadLine();
Console.WriteLine(―you look nice at‖+s);
}
}
TOKENS: The smallest, non-reducible, textual elements in a program are referred to as tokens.
The compiler recognizes them for building up expressions and statements. A C# program is a collection
of tokens, comments and whitespaces. The c# tokens are
 Keywords
 Identifiers
 Literals
 Operators
 Punctuators
meanings and these meanings cannot be changed. Keywords serve as basic building blocks for
program statements. All keywords must be written in lowercase. Keywords cannot be used as
identifiers except when they are prefaced by the @ character.

In C#, some identifiers have special meaning in context of code, such as get and set, these are called
contextual keywords.

IDENTIFIERS: An identifier is a name, which is used to identify a class, variable, function,


interface, namespace and label. The basic rules for framing identifiers in C# are as follows:
 They can have alphabets, digits (0 - 9), or underscore.
 They must not begin with a digit.
 Upper case and lower case letters are distinct.
 It should not be a C# keyword.
LITERALS: Literals are value constants assigned to variables in a program. C# supports several
types of literals.
Numeric literals:
Integer literals: An integer literal refers to a sequence of digits. There are two types of integers,
namely decimal and hexadecimal integers.
Decimal integers: Decimal integers contains a set of digits from 0 to 9 with an optional + or – sign
Example: Valid examples Invalid examples
1. 123 1. 153 43
2. –76565 2. 20,000
3. 0 3. $667
4. +736 4. 9-898
Hexadecimal integers: A sequence of digits preceded by 0x (or) 0X is considered as a hexadecimal
integer. It may also include alphabets A through F (or) a through f.A letter A through F represents
the numbers from 10 through 15.
Examples: Valid examples Invalid examples
1. 0x2 1.0xnmjk
2. 0x87665 2.0x1286m
3. 0xabc 3.08972
4. 0x53647 4.0khjdi
Real literals: The numbers containing fractional part is called real (or) floating-point literals. We
have two Notations for representing real literals.
 Decimal notation
 Scientific notation (or) exponential notation
Decimal notation: It represents numbers having a whole number followed by decimal point and
fractional part.
Example: 215.
.95
-.75
+.5
Scientific notation: A real number may also be expressed in exponential (or) scientific notation.
Example: The number 215.65 may be written as 2.1565e2 in exponential notation.e2 means multiply
by 102.
Syntax: mantissa e exponent
Mantissa: mantissa is either a real number expressed in decimal notation.
Exponent: It is an integer number with an optional sign.
E (or) e: It separates the mantissa and the exponent can be written in either uppercase (or) lower
case.
Example: 0.65e4
12e-2
1.5e+5
3.18e3
Exponential notation is useful for representing the numbers that are either very large (or) very small
in magnitude.
Example: 7500000000 is equals to 7.5e9 is also equals to 75e8
-0.000000368 is equals to -3.68e-7
Boolean literals: There are two Boolean literal values
true
false
Character literals:
Single Character Constants: A single character constant contains a single character enclosed by
single quote marks is called single character constants.
Examples: ‗a‘
‘#‘
‘2‘
‘‘
String Constants: A string constant is a sequence of characters enclosed by double quotes. The
character may be any letter, digits, special characters and blank space .
Example: ―Welcome to c programming‖
―2001‖
―Well done‖
―34+23‖
―d‖
BACKSLASH CHARACTER CONSTANTS: C# supports some special backslash character
constants that are used in output methods. Each backslash character constant contains two
characters to represent a single character. These combinations are called escape sequences.
1. \a – alert
2. \b – Backspace
3. \f – Form feed
4. \n – New line
5. \r – Carriage return
6. \t – Horizontal tab
7. \v – Vertical tab
8. \\ – Backslash
9. \' – Single quote
10. \" – Double quote
11. \0 - Null
DATA TYPES: Every variable in C# is associated with a data type.Data types specify the and size of
values that a variable can be stored. The data types in C# are primarily divided into two types.:
 Value types
 Reference types
Value types and reference types differ in two characteristics
 Where they are stored in the memory
 How they behave in the context of assignment statements.
Value Type: Value types (which are of fixed length) are stored on the stack(stack is a place where
the data stores in fixed length like float,int etc.), when a value of a variable is assigned to a variable
the value is actually copied. This means that two identical copies of the value are available in
The value types of C# can be grouped into two categories, namely,
 User defined types (or) complex types
 Predefined types (or) simple types

User defined types (or) complex types: Here we can define our own complex types known as
User defined value types, which includes
 structures
 enumerations
Predefined types: These are also known as simple types (or) primitive types. Predefined types are
divided into
 Numeric types
 Boolean types
 Character types
Numeric types: Numeric types include integral types, floating point types and decimal types.
Integral types: Integral types can hold whole numbers such as 123, -96 and 5639.The size of the
values that can be stored depends on the integral data type we choose. C# supports the concept of
unsigned types and therefore it supports eight types of integers .
Signed integers: signed integer types can hold both positive and negative numbers.
Type Size Minimum value Maximum value
sbyte 1 byte -128 +127
short 2 byte -32768 +32767
int 4 byte 2147483648 +2147483647
long 8 byte -9223372036854775808 +9223372036854775807
Unsigned integers: unsigned integer types can hold only positive numbers
Type Size Minimum value Maximum value
byte 1 byte 0 255
ushort 2 byte 0 65535
uint 4 byte 0 4294967295
ulong 8 byte 0 18446744073709551615
All integers are by default int type. In order to specify other integer types, we must append the
characters U,L or UL
 123U(for uint type)
 123L(for long type)
 123UL(for ulong type)
Floating point types: Floating point types hold numbers containing fractional parts such as 27.59
and -1.375.There are two kinds of Floating point storage in C#
The Floating point values are single-precision numbers with a precision of seven digits.
The double types represent double-precision numbers with a precision of 15/16 digits
Type Size Minimum value Maximum value
float 4 byte 1.5x10-45 3.4x1038
double 8 byte 5.0x10-324 1.7x10308
Floating point numbers by default as double-precision quantities.to force them to be in single
precision mode, we must append f (or) F to the numbers.
Example: 1.23f
7.56923f
Double-precision types are used when we need greater precision in storage of floating-point
numbers.
Floating-point data types support a special value known as Not-a-Number(NaN).NaN is used to
represent the result of operations such as dividing zero by zero,where an actual number is not
produced. Most operations NaN as an operand will produce NaN as result.
Decimal type: The decimal type is a high precision,128-bit data type that is designed for use in
financial monetary calculations. It can store values in the range 1.0x10 -28 to 7.9x1028 with 28
significant digits.
To specify a number to be decimal type, we must append the character M or mto the value.
Example: 123.45M (if we omit M, the value will be treated as double).
Character type: In order to store single characters in memory, C# provides a character data type
called char. The char type assumes a size of two bytes but, in fact it can hold only a single
character. char data type has been designed to hold a 16-bit Unicode character, in which 8-bit ASCII
code is a subset.
Boolean type: Boolean condition can be used when we want to test a particular condition during the
execution of the program. There are two values that a Boolean type can take true (or) false. Boolean
type can be denoted by the keyword bool and uses only one bit of storage.
Reference types: reference types (which are of variable length) are stored on the heap, and when an
assignment between two reference variables occurs, only the reference is copied. The actual values
remains in the same memory location. This means there are two references to a single value. The
reference types can be divided into two groups
 User defined types (or) complex types
 Predefined types (or) simple types
User defined types: user defined reference types refer to those types which we define using
predefined type. They include
 Classes
 Delegates
 Interfaces
 Arrays
Predefined types: Predefined types include two types
 Object type
 String type
VARIABLES: A variable is an identifier that denotes a storage location uses to store a data value.
Unlike constants that remain unchanged during the execution of the program, a variable may take
different values at different times during the execution of the program. Every variable has a type that
determines what values can be stored in the variable.
Rules for forming a variable:
 They must not begin with a digit.
 Uppercase and lower case is distinct. This means that the variable TOTAL is not same as
total or Total.
 It should not be a keyword.
 White space is not allowed.
 Variable names can be of any length.
Variable declaration: After designing suitable variable names, we must declare the variable before it
used in the program. Declaration does three things
 It tells the compiler what the variable name is.
 It specifies what type of data the variable will hold.
 The place of declaration in the program decides the scope of the variable.
Syntax: data_type variable1, variable2,……. variableN;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data
type, and variables are separated by commas. Some valid variable definitions are shown here:
int i, j, count;
float f, salary;
double pi;
byte b;
char c1,c2,c3;
decimal d1,d2;
uint m;
ulong n;
Initializing Variables: The process of giving initial values to the variables is called initialization. Once
the declaration has been done then initializes the variables with the assignment operator. The general
form of initialization is:
Syntax: variable_name = value;
It is also possible to assign a value at the time of its declaration.
Syntax: <data_type> <variable_name> =
value; Example:
int d = 3, f = 5;
byte z = 22;
double pi = 3.14159;
char x = 'x';
Example:
float x,y,z; //declares three variables
int m=5,n=10; //declares and initializes two int
variables int m, n=10; //declares m and n and initializes n.
Example: The following example uses various types of 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();
}
}
}
Output: a = 10, b = 20, c = 30
Scope of variables: The scope of the variable determines over what part(s) of the program a variable
is actually available for use (active).This depends on the type of the variable and place of its
declaration. C# defines several categories of variables.
 Static variables
 Instance variables
 Array elements
 Value parameters
 Reference parameters
 Output parameters
 Local variables
Example: class ABC
{
static int m;
int n;
void fun (int x , ref int y, out int z, int[] a)
{
int j = 10;
}
}
 m = static variable,
 n = instance variable,
 x = value parameter,
 y = reference parameter,
 j = local variable,
 z =output parameter,
 a[0] = array element
TYPE CONVERSION: The process of converting one data type into another data type is known as
type casting or type conversion. Type conversions are divided into two types.
1. Implicit (or) up casting (or) widening (or) automatic type conversion.
2. Explicit (or) down casting (or) narrowing type conversion.
Implicit type conversion (Automatic type conversion): Converting lower data type into higher
data type is called widening. In this one data type is automatically converted into another type as per
the rules described in c# language, which means the lower level data type is converted automatically
into higher level data type before the operation proceeds. The result of the data type having higher
level data type.
Example: byte x = 12;
int y = x;
In the above statement, the conversion of data from byte to int is done implicitly, in other words
programmers don‘t need to specify any type operators. Widening is safe because there will not be
any loss of data. This is the reason even though the programmer does not use the cast operator the
compiler does not complaint because of lower data type is converting into higher data type. Here
higher data type having the much more space to store the lower data type.
Example: using System;
namespace explicit_cast_conversion
{
class Program
{
static void Main(string[] args)
{
int num1=10;
long num2=num1;
Console.WriteLine("num2 value is : " +num2);
Console.ReadLine();
}
}
}
Explicit type conversion: Converting higher data type into lower data type is called
narrowing. Here we can place intended data type in front of the variable to be cast.
Syntax: data-type variablename1=(cast-
type)variablename2; Example: double d=12.67853;
int n = (int) d;
Here we are converting higher level data type into lower level data type that means double type is
converted into int type, the fractional part of the number is lost and only 12 is stored in n. Here we
are losing some digits this is the reason the compiler forces the programmer to use the cast operator
when going for explicit casting.

Example: The following example shows an explicit type conversion:


using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d = 5673.74;
int i;
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
Output: 5673
Microsoft .NET provides three ways of type conversion:
 Parsing
 Convert Class
 Boxing and unboxing
parsing: Parsing is used to convert string type data to primitive value type. For this we use parse
methods with value types.

Example:

using System;
class Program
{
static void Main()
{
string text = "500";// Convert string to number.
int num = int.Parse(text);
Console.WriteLine(num);
int num2 = int.Parse(Console.ReadLine());
Console.WriteLine(num2);
}
}
Example: using System;
namespace parsing
{
class Program
{
static void Main(string[] args)
{
int number;
float weight;
Console.Write("Enter any number : ");
number = int.Parse(Console.ReadLine());
Console.Write("Enter your weight : ");
weight = float.Parse(Console.ReadLine());
Console.WriteLine("You have entered : " + number);
Console.WriteLine("You weight is : " + weight);
Console.ReadLine();
}
}
}
Convert class: It is used to convert one primitive type to another primitive type. Convert is the
predefined class. C# provides the following built-in type conversion methods as described:
S.No Method Description
1 ToBoolean Converts a type to a Boolean value, where possible
2 ToByte Converts a type to byte.
3 TOChar Converts a type to single Unicode character, where possible.
4 ToDateTime Converts a type to date time structures.
5 ToDecimal Converts a floating point or integer type to decimal type.
6 ToDouble Converts a type to double type.
7 ToInt16 Converts a type to a 16-bit integer.
8 ToInt32 Converts a type to a 32-bit integer.
9 ToInt64 Converts a type to a 64-bit integer.
10 ToSbyte Converts a type to a signed byte type.
11 ToSingle Converts a type to a small floating point number.
12 ToString Converts a type to a string.
13 ToType Converts a type to a specified type.
14 ToUInt16 Converts a type to unsigned int type.
15 ToUInt32 Converts a type to unsigned long type.
16 ToUInt64 Converts a type to unsigned big integer.
Example: The following example converts various value types to string type:
using System;
namespace TypeConversionApplication
{
class StringConversion
{
static void Main(string[] args)
{
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();
}
}
}
Output: 75
53.005
2345.7652
True
Example:

using System;
namespace Arithmetic_Operators
{
class Program
{
static void Main(string[] args)
{
int num1, num2;
int add, sub, mul;
Console.Write("Enter first number\t\t");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("\n\nEnter second number\t\t");
num2 = Convert.ToInt32(Console.ReadLine());
add = num1 + num2;
sub = num1 - num2;
mul = num1 * num2;
Console.WriteLine("\n\n=============\n");
Console.WriteLine("Addition\t\t{0}", add);
Console.WriteLine("Subtraction\t\t{0}", sub);
Console.WriteLine("Multiplication\t\t{0}", mul);
Console.WriteLine("\n==============\n");
Console.ReadLine();

example: using System;


namespace convert_conversion
{
class Program
{
static void Main(string[] args)
{
string num = "23";
int number = Convert.ToInt32(num);
int age = 24;
string vote = Convert.ToString(age);
Console.WriteLine("Your number is : " + number);
Console.WriteLine("Your voting age is : " + age);
Console.ReadLine();
}
}
}
OPERATORS: An operator is a symbol that tells the computer to perform specific mathematical or
logical manipulations. Operators are used in programs to manipulate data and variables. C# has rich

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and decrement operators
 Conditional operators
 Bitwise Operators
 Special Operators
Arithmetic Operators: The operators that are used to perform Arithmetic operations such as
addition, subtraction, multiplication, ----etc. are called Arithmetic operators. Assume variable A
holds 10 and variable B holds 20 then:
Operator Meaning Description Example
+ Addition operator Adds two operands a+b=30
- Subtraction operator Subtracts second operand from the first a-b=-10
* Multiplication operator Multiplies both operands a*b=200
/ Division operator Divides numerator by de-numerator b/a=2
% Modulus division operator It gives Remainder after an integer division b%a=0
Integer Arithmetic: When both the operands in a single arithmetic expression such as a+b are
integers, the expression is called as integer expression and the operation is called integer arithmetic
The a=4, b=2, then
a+b = 6
a-b = 2
a*b = 8
a/b = 2
a%b = 0
Real Arithmetic: An arithmetic operation involving only real operands is called real arithmetic. A
real operand may assume values either in decimal or exponential notation.
Example: a=20.5F,b=6.4F
a+b =26.9
a-b = 14.1
a*b = 131.2
a/b = 3.203125
a%b = 1.3
Example:
Mixed-mode Arithmetic: When one of the operands is real and the other is integer, the expression is
called a mixed-mode arithmetic expression. If either operand is real type, then the other operand is
converted to real and real arithmetic is performed. The result will be real.
Example: 15/10.0=1.5
15.0/10=1
Example: The following example demonstrates all the arithmetic operators available in C#:
using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;
int c;
c = a + b;
Console.WriteLine("Line 1 - Value of c is {0}",
c); c = a - b;
Console.WriteLine("Line 2 - Value of c is {0}",
c); c = a * b;
Console.WriteLine("Line 3 - Value of c is {0}",
c); c = a / b;
Console.WriteLine("Line 4 - Value of c is {0}",
c); c = a % b;
Console.WriteLine("Line 5 - Value of c is {0}",
c); c = a++;
Console.WriteLine("Line 6 - Value of c is {0}",
c); c = a--;
Console.WriteLine("Line 7 - Value of c is {0}", c);
Console.ReadLine();
}
}
}
Output: Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Relational Operators: These operators are used to compare the value of two variables. Relational
operator‘s checks relationship between two operands. If the relation is true, it returns value
1 and if the relation is false, it returns value 0. Assume variable A holds 10 and variable B holds
20, then:
Operator Meaning Description Example
> Greater than Checks if the value of left operand is greater than (a>b)
the value of right operand, if yes then condition is not
becomes true. true
< Less than Checks if the value of left operand is less than (a<b)
the value of right operand, if yes then condition is
becomes true. true
<= Less than or equals to Checks if the value of left operand is less than or a<=b is
equal to the value of right operand, if yes then true
condition becomes true.
>= Greater than or equals to Checks if the value of left operand is greater than a>=b
or equal to the value of right operand, if yes then is not
condition becomes true. true
!= Not equals to Checks if the values of two operands are equal or a!=b
not, if values are not equal then condition is
becomes true. true
== Equals to Checks if the values of two operands are equal or a==b is
not, if yes then condition becomes true. not true
Example: The following example demonstrates all the relational operators available in C#:
using System;
class Program
{
static void Main(string[] args)
{
int a = 21;int b = 10;
if (a == b)
Console.WriteLine("Line 1 - a is equal to b");
else
Console.WriteLine("Line 1 - a is not equal to b");
if (a < b)
Console.WriteLine("Line 2 - a is less than b");
else
Console.WriteLine("Line 2 - a is not less than b");
if (a > b)
Console.WriteLine("Line 3 - a is greater than b");
else
Console.WriteLine("Line 3 - a is not greater than b");
a = 5;
b = 20;
if (a <= b)
Console.WriteLine("Line 4 - a<=b");
if (b >= a)
Console.WriteLine("Line 5-b >=b");
}
}
Output: Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Logical Operators: These operators are used to perform logical operations on the given two
variables. Logical operators are used to combine expressions containing relation operators.
Assume variable A holds Boolean value true and variable B holds Boolean value false, then:
Operator Meaning Description Example
&& Logical AND If both operands are non-zero then condition (a&&b) is false
becomes true
|| Logical OR If any of the two operands is non-zero then (a||b) is true
condition becomes true
! Logical NOT Used to reverse the logical state of its !(a&&b) is true
operand. If a condition is true then logical
NOT operator will make false.
Example: The following example demonstrates all the logical operators available in C#:
using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
bool a = true;
bool b =
true; if (a
&& b)
Console.WriteLine("Line 1 - Condition is true");
if (a || b)
Console.WriteLine("Line 2 - Condition is true");
/* lets change the value of a and b */
a = false;
b = true;
if (a && b)
Console.WriteLine("Line3-Condition is true");
else
Console.WriteLine("Line3-not true");
if (!(a && b))
Console.WriteLine("Line4-Condition is true");
Console.ReadLine();
}
}
}
Output: Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
Assignment Operators: These are used to assign the values for the variables in C# programs. The
most common assignment operator is =.The syntax is shown below:
data type Variable_name = expression;

Operator Meaning Example Same as

= Assignment a=b a=b


+= Addition assignment a+=b a=a+b
-= Subtraction assignment a-=b a=a-b
Operator Meaning Example Same as

*= Multiplication assignment a*=b a=a*b


/= Division assignment a/=b a=a/b
%= Modula division assignment a%=b a=a%b
Example: The following example demonstrates all the assignment operators available in C#:
using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int c;
c = a;
Console.WriteLine("Line 1 - =Value of c = {0}",
c); c += a;
Console.WriteLine("Line 2 - += Value of c = {0}", c);
c -= a;
Console.WriteLine("Line 3 - -=Value of c = {0}", c);
c *= a;
Console.WriteLine("Line 4 - *=Value of c = {0}",
c); c /= a;
Console.WriteLine("Line 5 - /=Value of c = {0}", c);
c = 200;
c %= a;
Console.WriteLine("Line 6 - %=Value of c = {0}", c);
Console.ReadLine();
}
}
}
Output: Line 1 - =Value of c = 21
Line 2 - += Value of c = 42
Line 3 - -= Value of c = 21
Line 4 - *= Value of c =
441 Line 5 - /= Value of c =
21 Line 6 - %= Value of c =
11
Increment/Decrement Operators: Increment operators are used to increase the value of the variable
by one and decrement operators are used to decrease the value of the variable by one in C programs.
Decrement operator: – -var_name; (or) var_name – -;
Increment Operators:
1. ++ is an increment operator. This is an unary operator.
2. It increments the value of the operand by one.
Syntax: Incrementoperator: ++var_name; (or) var_name++;
Post Increment:If the increment operator ++ is placed after the operand, then operator is called Post
Increment. As the name indicates Post indicates means increment after the operand value is used.
Pre Increment:If the increment operator ++ is placed before the operand. Then operator is called Pre
Increment. As the name indicates Pre indicates, increment before the operand value is used.
Decrement Operators:
 is a decrement operator. This is an unary operator.
 It decrements the value of the operand by one.
The decrement operator is classified into two
categories:
Post Decrement(Ex: a--) :If the decrement operator -- is placed after the operand. Then the operator is
called post decrement. So the operand value is used first and then the operand value is decremented
by 1.
Pre Decrement(Ex:--a) : If the decrement operator -- is placed before the operand then the
operator is called Pre decrement. So the operand value is decrement by 1 first and this
decremented value is used.
Example: using System;
class Program
{
static void Main(string[] args)
{
int i = 4;
i++;
Console.WriteLine(i);
++i;
Console.WriteLine(i); i--;
Console.WriteLine(i);
--i;
Console.WriteLine(i);
}
}
Example: using
System;
class Program
{
static void Main(string[] args)
{
int i = 4;int y = 0; y =
i++;
Console.WriteLine("i = " + i);
Console.WriteLine("y = " + y);
Console.WriteLine();
++i;
Console.WriteLine("i = " + i);
Console.WriteLine("y = " + y);
Console.WriteLine();
y = i--;
Console.WriteLine("i = " + i);
Console.WriteLine("y = " + y);
Console.WriteLine();
y = --i;
Console.WriteLine("i = " + i);
Console.WriteLine("y = " +
y);
}
}
Conditional Operators:The conditional operator is also called a ternary operator. As the name
indicates an operator that operates on three operands is called ternary operator.The ternary operators
consisting two symbols i.e ? and :
Syntax: (Condition? true_value: false_value);
Where condition is an expression evaluated True or False.If condition is evaluated to True, the
ture_value is executed.If condition is evaluated to False, the false_value is executed.
Bitwise Operator: A bitwise operator works on each bit of data. Bitwise operators are used in
bit level programming
x y x|y x&y x^y Operator Description
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ One‘s
compliment
1 1 1 1 0 ^ XOR
<< Left Shift
>> Right Shift
Example: The following example demonstrates all the bitwise operators available in C#:
using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
Console.WriteLine("Line 1 - Value of c is {0}", c
); c = a | b; /* 61 = 0011 1101 */
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a ^ b; /* 49 = 0011 0001 */
Console.WriteLine("Line 3 - Value of c is {0}",
c); c = ~a; /*-61 = 1100 0011 */
Console.WriteLine("Line 4 - Value of c is {0}",
c); c = a << 2; /* 240 = 1111 0000 */
Console.WriteLine("Line 5 - Value of c is {0}",
c); c = a >> 2; /* 15 = 0000 1111 */
Console.WriteLine("Line 6 - Value of c is {0}", c);
Console.ReadLine();
}
}
}
Output: Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Miscellaneous Operators: There are few other important operators including sizeof, typeof and ? :
supported by C#.

Example: using System;


namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
/* example of sizeof operator */
Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of short is {0}", sizeof(short));
Console.WriteLine("The size of double is {0}", sizeof(double));
/* example of ternary
operator */ int a, b;
a = 10;
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of
b is {0}", b); b = (a == 10) ?
20 : 30;
Console.WriteLine("Value of b is
{0}", b); Console.ReadLine();
}
}
}
Output: The size of int is 4
The size of
short is 2
The size of
double is 8
Value of b
is 30
Value of b is 20

**********UNIT-1 COMPLETED******

You might also like