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

C Sharp Notes PART 1

C# is an object-oriented programming language developed by Microsoft that can be used to create a variety of applications that run on the .NET Framework. It provides strong programming features like interoperability, security, debugging support, and automatic garbage collection. C# code is typically written in Visual Studio using classes, methods, and other basic programming elements. The Console class allows C# programs to perform input and output to the console screen using methods like WriteLine and ReadLine.

Uploaded by

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

C Sharp Notes PART 1

C# is an object-oriented programming language developed by Microsoft that can be used to create a variety of applications that run on the .NET Framework. It provides strong programming features like interoperability, security, debugging support, and automatic garbage collection. C# code is typically written in Visual Studio using classes, methods, and other basic programming elements. The Console class allows C# programs to perform input and output to the console screen using methods like WriteLine and ReadLine.

Uploaded by

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

Programming in C#

C# is a modern, general-purpose, object-oriented programming language developed by


Microsoft 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.
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.
Strong Programming Features of C# (C# and .NET)
C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and
robust applications that run on the .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.
CLR extends number of benefits to C# when it is implemented on .NET platform. These include
• Interoperability with other languages
• Enhanced security
• Versioning support
• Debugging support
• Automatic Garbage Collection
• Delegates and Events Management
• XML support for web applications
• Easy-to-use Generics
• Indexers
• Conditional Compilation
• Simple Multithreading
• LINQ and Lambda Expressions

CS DEPT VC PUTTUR-II SEM BCA C# study Material 1


C# Environment and C# Basics
Integrated Development Environment (IDE) for C#
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.
Visual C# Express and Visual Web Developer Express edition are trimmed down versions of
Visual Studio and has the same appearance. They retain most features of Visual Studio. In this
tutorial, we have used Visual C# 2010 Express.
You can download it from Microsoft Visual Studio. It gets installed automatically on your
machine.
Creating first C# Program -Hello World class
A General structure of 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":
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

CS DEPT VC PUTTUR-II SEM BCA C# study Material 2


Let us look at the various parts of the given program:
• The first line of the program using System; - the using keyword is used to include
the System namespace in the program. A program generally has
multiple using statements.
• The next line has the namespace declaration. A namespace is a collection of classes.
The HelloWorldApplication namespace contains the class HelloWorld.
• The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods. Methods
define the behavior of the class. However, the HelloWorld class has only one
method Main.
• 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 addcomments in the
program.
• The Main method specifies its behavior with the statementConsole.WriteLine("Hello
World");
WriteLine is a method of the Console class defined in the Systemnamespace. 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.
• 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.

CS DEPT VC PUTTUR-II SEM BCA C# study Material 3


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.

using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}

C # Input & Output - The Console Class


The Console class provides a C# application with access to the standard input, standard output,
and standard error streams. Standard input is normally associated with the keyboard—anything
that the user types on the keyboard can be read from the standard input stream. Similarly, the
standard output stream is usually directed to the screen, as is the standard error stream.

Write and WriteLine Methods


You can use the Console.Write and Console.WriteLine methods to display information on the
console screen. These two methods are very similar; the
main difference is that WriteLine appends a new line/carriage return pair to the end of the
output, and Write does not. Both methods are overloaded. You can call them with variable
numbers and types of parameters. For example, you can use the following code to write “99” to
the screen:
Console.WriteLine(99);
You can use the following code to write the message “Hello, World” to the screen:
Console.WriteLine(“Hello, World”);

CS DEPT VC PUTTUR-II SEM BCA C# study Material 4


The Read Method
Read reads the next character from the keyboard. It returns the int value –1 if there is no more
input available. Otherwise it returns an int representing the character read.

The ReadLine Method


ReadLine reads all characters up to the end of the input line (the carriage return character). The
input is returned as a string of characters. You can use the following code to read a line of text
from the keyboard and display it to the screen:

string input = Console.ReadLine( );


Console.WriteLine(“{0}”, input);

Multiple Main functions in C#


c# enables us to define more than one class with the method. Main method is the entry point for
program execution.
Class Example_1
{
public static void Main()
{
System.Console.WriteLine("Example 1")
}

public void test()


{
System.Console.WriteLine("Test method")
}
}

Class Example_2
{
public static void Main()
{
System.Console.WriteLine("Example 2")
}
}

But while executing the program only one Main() method can be used for execution.
As in given program there are two class A and B in which each containing A Main Method. We
may write as
csc filename.cs /main:A [ for Class A Main Execution ] or,
csc filename.cs /main:B [ for Class B Main Execution ]

CS DEPT VC PUTTUR-II SEM BCA C# study Material 5


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.
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 namedlength 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.
C# command line arguments
We can pass command line arguments to C# programs. The program accept arguments in the
order of args[0], args[1] etc. The following program shows how to pass command line arguments
to the c# program. Open a new text document and copy and paste the following source code and
save the file as "NewProg.cs"
using System;

class NewProg
{
static void Main(string[] args)
{
Console.WriteLine("Arguments-1 " + args[0]+" Argument-2 "+args[1]);
Console.ReadKey();
}
}

Go to the command prompt and issue the following command for compilation.
csc NewProg.cs
After the successful compilation you will get NewProg.exe file

CS DEPT VC PUTTUR-II SEM BCA C# study Material 6


When you execute this C# program you have to pass two arguments with the filename.

NewProg test1 test2

you will get the output like Arguments-1 test1 Argument-2 test2

CS DEPT VC PUTTUR-II SEM BCA C# study Material 7


C# is freeform Language

A free-form language is a computer language in which coding can be positioned on any line and
still be valid. This means that a code can start on one line, end several lines down and still be a
valid statement.

For example

System.console.WriteLine(“Hello”); can be written as

System.Console.WriteLine
(
“Hello”
)

___________

CS DEPT VC PUTTUR-II SEM BCA C# study Material 8


C# Identifiers , Literals and Data types

C # 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.
• 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.

C# Constants and Literals


Constants refer to fixed values that the program cannot alter during its execution. These fixed
values are also called literals. Constants can be of any of the basic data types like an integer
constant, a floating constant, a character constant, or a string literal. There are also enumeration
constants as well.

CS DEPT VC PUTTUR-II SEM BCA C# study Material 9


The constants are treated just like regular variables except that their values cannot be modified
after their declaration.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or
radix: 0x or 0X for hexadecimal, 0 for octal and no prefix is required for decimal numbers.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals.
Integer Literal Sequence Meaning
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix (U is repeated)*/
The following are other examples of various types of integer literals:
Integer Literal Sequence Meaning
85 /* decimal literal*/
0213 /* octal literal */
0x4b /* hexadecimal literal */
30 /* int literal */
30u /* unsigned int literal */
30l /* long literal */
30ul /* unsigned long literal */

Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part and an exponent part.
You can represent floating point literals either in decimal form or exponential form.
Here are some examples of floating-point literals:
Floating-Point Literals Sequence Meaning
Double f=3.14159 /* Legal */
Double f=314159E-5 /* Legal */
Double f=510E /* Illegal: incomplete exponent */
Double f=210f /* Legal */
Double f=.e55 /* Illegal: missing integer or fraction */
Character Constants
Character literals are enclosed in single quotes, for example, 'x' and can be stored in a simple variable
of char type. A character literal can be a plain character (for example, 'x'), an escape sequence (for
example, ' \t'), or a universal character (for example, '\u02B0').

CS DEPT VC PUTTUR-II SEM BCA C# study Material 10


There are certain characters in C# that, when preceded by a backslash, will have a special meaning
that they are used to represent. For examle newline (\n) and tab (\t). The following is a list of some of
the escape sequence codes:
Escape Sequence Meaning
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhhh . . . Hexadecimal number of one or more digits

Defining Constants

Constants are defined using the const keyword. The following is the syntax for defining a constant:
const <data_type> <constant_name> = value;
The following program demonstrates defining and using a constant in your program:
using System;
namespace DeclaringConstants
{
class Program
{
static void Main(string[] args)
{
const double pi = 3.14159;

// constant declaration
double r;
Console.WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());
double areaCircle = pi * r * r;
Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console.ReadLine();
}
}
}

CS DEPT VC PUTTUR-II SEM BCA C# study Material 11


C# Data Types
The varibles in C#, are categorized into the following types:
• Value types
• Reference types
• Pointer types

Classification of data types

Predefined Data type classification


Value Type
Value type variables can be assigned a value directly. They are derived from the
class System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which stores
numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the
system allocates memory to store the value.
The following table lists the available value types in C#

CS DEPT VC PUTTUR-II SEM BCA C# study Material 12


Type Represents Range Default
Value

bool Boolean value ( 1 bit) True or False False

byte 8-bit unsigned integer 0 to 255 0

char 16-bit Unicode character U +0000 to U +ffff '\0'

decimal 128-bit precise decimal values with 28-29 (-7.9 x 1028 to 7.9 x 1028) / 0.0M
significant digits 100 to 28

double 64-bit double-precision floating point type (+/-)5.0 x 10-324 to (+/-)1.7 x 0.0D
10308

float 32-bit single-precision floating point type -3.4 x 1038 to + 3.4 x 1038 0.0F

int 32-bit signed integer type -2,147,483,648 to 0


2,147,483,647

long 64-bit signed integer type -9,223,372,036,854,775,808 0L


to
9,223,372,036,854,775,807
sbyte 8-bit signed integer type -128 to 127 0

short 16-bit signed integer type -32,768 to 32,767 0

uint 32-bit unsigned integer type 0 to 4,294,967,295 0

ulong 64-bit unsigned integer type 0 to 0


18,446,744,073,709,551,615

ushort 16-bit unsigned integer type 0 to 65,535 0

To get the exact size of a type or a variable on a particular platform, you can use
the sizeof method. The expression sizeof(type) yields the storage size of the object or type in
bytes. Following is an example to get the size of int type on any machine:

CS DEPT VC PUTTUR-II SEM BCA C# study Material 13


using System;
namespace DataTypeApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
C# Integer Variable Types
Perhaps the most widely used of the variable types is the integer. C# provides a number of
different integer types based on number size and whether the integers are signed (positive or
negative) or unsigned (positive only). All the integer variable types have one thing in common
and that is that they may only be used to store whole numbers.
The following table lists the various C# integer variable types together with details of the number
of bytes of physical memory consumed by each type and the acceptable value ranges.
Type Size in Bytes Value Range
byte 1 byte 0 to 255
sbyte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
ushort 2 bytes 0 to 65,535
int 4 bytes -2,147,483,648 to 2,147,483,648
uint 4 bytes 0 to 4,294,967,295
long 8 bytes -1020 to 1020
ulong 8 bytes 0 to 2 x 1020
C# Floating Point Variables
Integers are fine for dealing with whole numbers but of little use when there are numbers after
the decimal point. Such numbers may be stored in float or double variable types. The default
type for such numbers is double. The following table shows the two types with comparisons of
the number ranges supported and the number of significant digits in each case:
Type Size in Bytes Value Range Digit Accuracy
float 4 bytes 1.5 * 10-45 to 3.4 * 1038 6 - 7 digits
double 8 bytes 5.0 * 10-324 to 1.7 * 10308 15 - 16 digits
It is important to note that float and double variables cannot be used as counting variables (for
example in looping constructs).
The C# Decimal Variable Type
Both the integer and floating point families of C# variable types have some limitations. Integers
can only handle whole numbers, resulting in the fractional part of a value being stripped off.
Floats, on the other hand, have problems with rounding accuracy. Clearly the best of both worlds
CS DEPT VC PUTTUR-II SEM BCA C# study Material 14
is sometimes needed and to address this requirement the decimal variable type is provided.
The decimal type is a compromise between integer and float variable types in that it can store
fractional parts of a value and provide exact values in computations.
The decimal variable type is capable of holding values in the range 10-28 all the way up to
1028 with none of the rounding problems associated with floating point variable types.
C# Boolean Variable Type
The C# Boolean variable type is declared using the bool keyword and allows for the storage
of true and false values. Boolean variables are particularly useful in flow control constructs such
as if and while statements.
Unlike some other programming languages, C# boolean variables must be assigned
either true or false and cannot be assigned 1 or 0:
bool loopFinished = false;

loopFinished = true;
C# Character Variable Type
When we talk about characters we are referring to individual letters and numbers. For example,
the letter 'a' is a character, as is the visual representation of the number '1'. Such characters may
be stored in a C# char variable. A char variable can contain one character and one character
only. It is important to be aware that a character is not limited to those in the English alphabet. A
character stored in a char variable can be Chinese, Japanese, Arabic, Cyrillic, Hebrew or any
other type of character you care to mention.
In addition, characters can be used for counting in loops and even in mathematical expressions.
To assign a character to a variable simply surround the character with singe quotes:
char myLetter = 'a';
C# provides a number of special character constants which have a special meaning when
displayed. These special constants perform such tasks as displaying tab and new lines in text.
The following table lists the characters, all of which are identified by a preceding backslash (\):
Character Constant Special Value
\n New Line
\t Tab
\0 Null
\r Carriage Return
\\ Backslash
Note that there is a special character sequence for the Backslash (\\). Because the special
characters begin with a backslash the compiler interprets any instances of a single backslash as
the pre-cursor to a special character. This raises the question of what to do if you really want a
backslash. The answer is to use the double backslash special constant sequence.
C# String Variables
In the preceding section we looked at storing individual characters in a char variable. Whilst this
works for storing a single letter or number it is of little use for storing entire words or sentences.

CS DEPT VC PUTTUR-II SEM BCA C# study Material 15


For this purpose the string variable type is supported by C#. Variables of type string can store a
string of any number of characters.
String values are surrounded by double quotes ("). For example:
string myString = "This is a string";
A string declaration in C# cannot be spread over multiple lines. If a string needs to be split over
multiple lines by new lines the \n special character can be used. For example:
string myString = "This is line one\nThis is line two\nThis is line 3";

System.Console.WriteLine (myString);
The above example code will result in the following output:
This is line one
This is line two
As a matter of fact, any of the special characters outlined in the preceding section on
the char type may be embedded into string.
Reference Type
The reference types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference types
can refer to a memory location. If the data in the memory location is changed by one of the
variables, the other variable automatically reflects this change in value. Example of built-
in reference types are: object,dynamic, and string.
Difference between a Value Type and a Reference Type
The Types in .NET Framework are either treated by Value Type or by Reference Type. A Value
Type holds the data within its own memory allocation and a Reference Type contains a pointer to
another memory location that holds the real data. Reference Type variables are stored in the heap
while Value Type variables are stored in the stack.

Value Type:
A Value Type stores its contents in memory allocated on the stack. When you created a Value
Type, a single space in memory is allocated to store the value and that variable directly holds a
value. If you assign it to another variable, the value is copied directly and both variables work
independently. Predefined datatypes, structures, enums are also value types, and work in the
same way. Value types can be created at compile time and Stored in stack memory, because of
this, Garbage collector can't access the stack.

CS DEPT VC PUTTUR-II SEM BCA C# study Material 16


e.g.
int x = 10;
Here the value 10 is stored in an area of memory called the stack.
Reference Type:
Reference Types are used by a reference which holds a reference (address) to the object but not
the object itself. Because reference types represent the address of the variable rather than the data
itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second
copy of the reference, which refers to the same location of the heap as the original value.
Reference Type variables are stored in a different area of memory called the heap. This means
that when a reference type variable is no longer used, it can be marked for garbage collection.
Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc.
e.g.

int[] iArray = new int[20];


In the above code the space required for the 20 integers that make up the array is allocated on the
heap.

_____________________

CS DEPT VC PUTTUR-II SEM BCA C# study Material 17


Operators & Expressions

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C# has rich set of built-in operators and provides the following type of
operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and other operators
one by one.
Arithmetic Operators
Following table shows all the arithmetic operators supported by C#. Assume variable A holds
10 and variable B holds 20 then:

Operator Description Example

+ Adds two operands A + B = 30

- Subtracts second operand from the first A - B = -10

* Multiplies both operands A * B = 200

/ Divides numerator by de-numerator B/A=2

% Modulus Operator and remainder of after an integer division B%A=0

++ Increment operator increases integer value by one A++ = 11

-- Decrement operator decreases integer value by one A-- = 9

Relational Operators
Following table shows all the relational operators supported by C#. Assume variable A holds 10
and variable B holds 20, then:

Description Example
Operator

== Checks if the values of two operands are equal or not, if yes then (A == B)
condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not, if values are (A != B)
not equal then condition becomes true. is true.

CS DEPT VC PUTTUR-II SEM BCA C# study Material 18


> Checks if the value of left operand is greater than the value of right (A > B)
operand, if yes then condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of right (A < B)
operand, if yes then condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to the (A >= B)
value of right operand, if yes then condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the (A <= B)
value of right operand, if yes then condition becomes true. is true.

Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds
Boolean value true and variable B holds Boolean value false, then:

Operator Description Example

&& Called Logical AND operator. If both the operands are non zero (A &&
then condition becomes true. B) is
false.

|| Called Logical OR Operator. If any of the two operands is non (A || B)


zero then condition becomes true. is true.

! Called Logical NOT Operator. Use to reverses the logical state of !(A &&
its operand. If a condition is true then Logical NOT operator will B) is
make false. true.

Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^
are as follows:
p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; then in the binary format they are as follows:
A = 0011 1100
B = 0000 1101

CS DEPT VC PUTTUR-II SEM BCA C# study Material 19


-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table. Assume variable A
holds 60 and variable B holds 13, then:

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12,
both operands. which is 0000
1100

| Binary OR Operator copies a bit if it exists in either (A | B) = 61,


operand. which is 0011
1101

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) = 49,


operand but not both. which is 0011
0001

~ Binary Ones Complement Operator is unary and has the (~A ) = 61, which
effect of 'flipping' bits. is 1100 0011 in 2's
complement due
to a signed binary
number.

<< Binary Left Shift Operator. The left operands value is A << 2 = 240,
moved left by the number of bits specified by the right which is 1111
operand. 0000

>> Binary Right Shift Operator. The left operands value is A >> 2 = 15,
moved right by the number of bits specified by the right which is 0000
operand. 1111

Assignment Operators
There are following assignment operators supported by C#:

Operator Description Example

= Simple assignment operator, Assigns values from right side C=A+B


operands to left side operand assigns value
of A + B into
C

CS DEPT VC PUTTUR-II SEM BCA C# study Material 20


+= Add AND assignment operator, It adds right operand to the C += A is
left operand and assign the result to left operand equivalent to
C=C+A

-= Subtract AND assignment operator, It subtracts right operand C -= A is


from the left operand and assign the result to left operand equivalent to
C=C-A

*= Multiply AND assignment operator, It multiplies right C *= A is


operand with the left operand and assign the result to left equivalent to
operand C=C*A

/= Divide AND assignment operator, It divides left operand C /= A is


with the right operand and assign the result to left operand equivalent to
C=C/A

%= Modulus AND assignment operator, It takes modulus using C %= A is


two operands and assign the result to left operand equivalent to
C=C%A

<<= Left shift AND assignment operator C <<= 2 is


same as C = C
<< 2

>>= Right shift AND assignment operator C >>= 2 is


same as C = C
>> 2

&= Bitwise AND assignment operator C &= 2 is


same as C = C
&2

^= bitwise exclusive OR and assignment operator C ^= 2 is


same as C = C
^2

|= bitwise inclusive OR and assignment operator C |= 2 is same


as C = C | 2

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

Operator Description Example

sizeof() Returns the size of a data type. sizeof(int), returns 4.

typeof() Returns the type of a class. typeof(StreamReader);

& Returns the address of an variable. &a; returns actual address

CS DEPT VC PUTTUR-II SEM BCA C# study Material 21


of the variable.

* Pointer to a variable. *a; creates pointer named


'a' to a variable.

?: Conditional Expression If Condition is true ?


Then value X : Otherwise
value Y

is Determines whether an object is of a certain type. If( Ford is Car) // checks


if Ford is an object of the
Car class.

as Cast without raising an exception if the cast fails. Object obj = new
StringReader("Hello");
StringReader r = obj as
StringReader;

Operator Precedence in C#
Operator precedence determines the grouping of terms in an expression. This affects evaluation
of an expression. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so the first evaluation takes place for 3*2 and then 7 is added into it.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators are evaluated first.
Show Examples
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

CS DEPT VC PUTTUR-II SEM BCA C# study Material 22


Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Type Conversions
Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#,
type casting has two forms:
• Implicit type conversion - These conversions are performed by C# in a type-safe
manner. For example, are conversions from smaller to larger integral types and
conversions from derived classes to base classes.

Explicit type conversion - These conversions are done explicitly by users using the pre-
defined functions. Explicit conversions require a cast operator.
Implicit Conversion
In implicit conversion the compiler will make conversion for us without asking.
char -> int -> float is an example of data compatibility.
Complier checks for type compatibility at compilation.

Example

using System;

namespace implicit_conversion
{
class Program
{
static void Main(string[] args)
{
int num1 =20000;
int num2 =50000;
long total;
// In this the int values are implicitly converted to long data type;
//you need not to tell compiler to do the conversion, it automatically does.
total = num1 + num2;

Console.WriteLine("Total is : " + total);


Console.ReadLine();
}
}
}

CS DEPT VC PUTTUR-II SEM BCA C# study Material 23


Below table shows the implicitly type conversions that are supported by C#:

From To
sbyte short, int, long, float, double, decimal
byte short, ushort, int, uint, long, ulong, float, double, decimal
short int, long, float, double, decimal
ushort int, uint, long, ulong, float, double, decimal
int long, float, double, decimal
uint long, ulong, float, double, decimal
long float, double, decimal
ulong float, double, decimal
float double
char ushort, int, uint, long, ulong, float, double, decimal
Explicit Conversion
In explicit conversion we specifically ask the compiler to convert the value into another data
type.
CLR checks for data compatibility at runtime.
Explicit conversion is carried out using casts. When we cast one type to another, we deliberately
force the compiler to make the transformation.

You should never expect that the cast would give you best or correct result. Casts are potentially
unsafe. Casting of big data type into small may lead to loosing of data.
Example
using System;
class ExplicitConversion
{
static void Main(string[] args)
{ double d = 5673.74;
int i;
i = (int)d; // cast double to int.
Console.WriteLine(i);
}
}
}
Boxing and Unboxing
Boxing is the process of converting a value type to the type object or to any interface type
implemented by this value type. When the CLR boxes a value type, it wraps the value inside a
System.Object and stores it on the managed heap. Unboxing extracts the value type from the
object. Boxing is implicit; unboxing is explicit.
In the following example, the integer variable i is boxed and assigned to object o.
int i = 123;
// The following line boxes i.
object o = i;
The object o can then be unboxed and assigned to integer variable i:

o = 123;
i = (int)o; // unboxing
_____________

CS DEPT VC PUTTUR-II SEM BCA C# study Material 24

You might also like