You are on page 1of 62

An introduction to C#

CSharp is an Object Oriented Language , introduced in the .NET Framework. C# is a


professional programming language and is very similar to C++ in many ways. We can
implement the Object Oriented concepts like encapsulation, inheritance, and
polymorphism in C# programming development .
C# is a Simple, Powerful , general-purpose and Type-Safe language also Case Sensitive . We
can develop C# projects in Visual StudioEnvironment , a powerful tool-rich programming
environment from Microsoft. We can create console based applications as well as windows
based applications from C# environment. C# Coding style is very similar to C++ and JAVA ,
so the developers who are familiar with those languages can pick up C# coding quickly.
C# and VB.NET
CSharp and VB.NET are the two primary languages used to program on the .NET
Framework environment. Both languages are use the same framework and they both
precompiled into the same byte code and then it is compiled and run at runtime. So we can
say VB.NET and C# are functionally equivalent. Both C# and Visual Basic.NET share
structural similarities with other modern high level languages such as Java and C++ .
But both have different in many features. Primarily keywords are different in each other
language . C# is case sensitive while Visual Basic .NET is not. In VB.NET "Example" and
"example" are same , but in CSHARP "Example" and "example" are two different variable
names. Also it is good to remember that C# statements always terminated by a semicolon
(;).
The following are some examples of differences between VB.NET and C#.
Single Line Comments :
VB.NET : ' ex: 'This is a single line comment
CSHARP : // ex: //This is a single line comment
Multi Line Comments :
VB.NET : Not available
CSHARP : /*..*/ ex: /*Multi line comments */
Conditional Statements
VB.NET
If condition Then
'vb.net code
Else
'vb.net code
End If
CSHARP
if(condition)
{
//csharp code
}
else
{
//csharp code
}
Loops
VB.NET
For counter As Integer = 0 To final
'vb.net code
Next
CSHARP
for(int i=0;i < final;i++)
{
//csharp code
}
Operator (Equal)
VB.NET
a=b
CSHARP
a==b;
Declaration
VB.NET
Dim i as Integer = 10
CSHARP
int i=10;
Click the following link to learn more about VB.NET and C# Keywords differences
CSharp VB.Net comparison
C# and JAVA
C# and JAVA are two different Object Oriented Languages , both have some similarities
and differences also. The Csharp and JAVA derived from their own single ancestor Class
"Object". All Classes in C# are descended from System.Object Class and in JAVA all classes
are subclasses of java.lang.Object Class. C# tries to be modern, to shine with new features,
to ride ahead of time, to adopt cryptic syntax for things. C# is more a "commercial"
language with many powerful libraries commercially available. While Java tries to be
conservative, slowly adopting new things, stable, clear, plain, easily understandible by a
beginner. Java is more like an "opensource" language with tons and tons of opensource
libraries available.
Runtime Environments
Both C# and JAVA have their own runtime environments . C# source codes are compiled to
Microsoft Intermediate Language (MSIL) and during the execution time runs it with the
help of runtime environments - Common Language Runtime (CLR). Like that JAVA source
codes are compiled to Java Byte Code and during the execution time runs it with the help of
runtime environments - Java Virtual Machine (JVM). Both CSharp and JAVA supports native
compilation via Just In Time compilers.
Type-Safe Languages
Java and C# were designed to be type-safe . An illegal casting will be caught at compile
time if it can be shown that the cast is illegal; or an exception will be thrown at runtime if
the object cannot be cast to the new type. Type safety is therefore more important because
it not only forces a programmer to write more correct code, but also helps a system become
more secure from code hackers.
Garbage Collection
In lower-level languages, memory management can be tedious work because you have to
remember to properly delete new objects to free up resources. That’s not the case
in C# and Java , where built-in garbage collection helps prevent memory leaks by removing
objects that are no longer being used by the application. While memory leaks can still
occur, the basics of memory management have already been taken care of for you.
Generics
Generics improve compiler-assisted checking of types largely by removing casts from
source code. In Java, generics are implemented using erasures. Generic type parameters
are "erased" and casts are added upon compilation into bytecode. C#takes generics even
further by integrating it into the Common Language Infrastructure (CLI) and allowing type
information to be available at runtime, yielding a slight performance gain.
Pointers
C# allows the use of pointers, which some language designers consider to be unsafe, but
certain language features try to ensure this functionality is not misused
accidentally. Pointers also greatly complicate technologies such as Java's Remote Method
Invocation (RMI), where program objects resident on one computer can be referenced
within a program running on an entirely separate computer. Some have speculated that the
lack of memory pointers in Java was a nod towards the coming of grid computing, where a
single application may be distributed across many physical pieces of hardware.
Methods
Methods in c-sharp are non-virtual by default. In Java however, methods are virtual by
default. Virtual methods guarantee that the most overridden method of an object will be
called which is determined by the runtime . You always have to keep that in mind when
calling or writing any virtual method! If the method is declared as non-virtual, the method
to invoke will be determined by the compiler. This is a major difference of philosophy
between the designers of the Java and .NET platforms.
C# sample programs
C# allows us to write programs like Console Bases Applicationsas well as Windows
Based Applications . The following links give you a basic idea of Console Based
Application and Windows Based Application.
C# console based application
Console programs are easy to develop, because console based
applications perform all their input and output at the command line,
they are ideal for quickly trying out language features and writing
command-line utilities. If you have ever learned a programming
language, you know that they all start with the "Hello, world!" program.
Here also we start with the "Hello, world!".
Hello World - Your First Program
In order to create a C# console based application
1. Open your Visual Studio
2. On the File menu, click New Project.
Then the New Project dialog box appears. This dialog box lists the different default
application types.
3. Select Console Application as your project type and change the name of your application
at the bottom textbox.
If you are npt comfortable with default location, you can always enter a new path if you
want.
4. Then Click OK.
After click OK button, you will get a screen like the following picture.

Here in the following program, we just print a "Hello, world!" message only. So copy and
paste the following command in the main code block.

Console.WriteLine("Hello, world!");
Here you can see the full source code.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}
}
After enter the command, the next step is to run the program. You can run your program
using Ctrl+F5 . Then Visual Studio will keep the console window open, until you press a
key. You will get screen look like the following picture.

Now you created your first program in Visual Studio.


How to stop C# console applications of closing automatically
The first program is to run your application by using Ctrl+F5, so the console window will
remain open until you press a key. The disadvantage of this (Ctrl+F5) is that you lose Visual
Studio's debug information. If you run your console application by using F5 instead of
Ctrl+F5 , you can see the window will disappear suddenly. It is because you program is
finished. When console applications have completed executing and return from their main
method, the associated console window automatically closes. This is expected behavior.
Prevent a C# Console Application from closing when it finishes
If you want to keep the application open for debugging purposes, you'll need to instruct the
computer to wait for a key press before ending the app and closing the window. In this case
you can use Console.ReadLine() to wait for the user to Enter or Console.ReadKey to wait for
any key.

Console.ReadLine();
Console.ReadKey();
Full Source:

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
Console.ReadLine();
}
}
}
C# Command Line Parameters
In some situations, you have to send command line parameters to your application. When
you pass arguments, the command line input, read from the standard entry point as string
array.

static int Main(string[] args)


The arguments of the Main method is a String array that represents the command-line
arguments. Usually you determine whether arguments exist by testing the Length property.

if (args.Length == 0)
{
System.Console.WriteLine("No arguments found!!");
return 1;
}
The main program accept arguments in the order of args[0], args[1] etc. The following
program shows how to display all parameters enter to the console application.

using System;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Number of command line arguments = {0}",args.Length);
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
}
}
}
}
How to pause console application
System.Threading.Thread.Sleep() will delay your programs. It receives a value indicating
the number of milliseconds to wait. This can be useful for waiting on an external
application or task.

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Pausing 5 seconds");
System.Threading.Thread.Sleep(5000);
}
}
When you run the above program, it will wait for 5 seconds and exit from application.
How do I correctly exit from a console application
A console application will just terminate when it's done, generally when it runs to the end
of its Main entry point method. A "return" will achieve this.

using System;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I am in the Loop !!!!");
return; //This will exit the console application's running thread
}
}
}
}

Console based applications will exit when the main function has finished running, though
you must be careful to get rid of any lingering resources you might have been managing, as
they can keep the underlying process alive. In some situations you may have to forcefully
terminate your program. In this case you can explicitly exit using Environment.Exit.
SystemEnvironment.Exit();

If you're returning an error code you can do it this way, which is accessible from functions
outside of the initial thread:

System.Environment.Exit(-1);
C# command line tools
CSC is the command for compiling the CSharp source code onCommand Line . When you
run the CSC Command on Command line the program generate a .EXE file. Create new Text
document and copy and paste the following source code save it as NewProg.cs .

using System;

class NewProg
{
static void Main(string[] args)
{
Console.WriteLine("My First Program");
Console.ReadKey();
}
}

Go to the command prompt and issue the following command for compilation.
csc NewProg.cs

When the compiler compile the program , if any error occurred in the source code , it will
display in the command prompt

After the successful compilation you will get NewProg.exe file

You can execute the file in the command prompt by giving exe file name (NewProg)
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

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
Introduction to C# Programming

C# also called as C-Sharp is a new Programming language which is developed by Microsoft


in 1995. C# language is also an pure object oriented programming language and it is made
from c, c++ ,and java programming languages and this is purely web based language. C# is
also known as component Oriented Language which uses in .NET framework Always
Remember all the Major Code of .NET is written into C# language.
In Early days there many programming languages were developed and they are used by
developers according to their needs. Early Programming Languages have a business
Environment and Scientific Environment So that there was no Programming Languages for
all purpose. All Programming Languages have some Limitations those are as follows:-
1) They have high Complexity
2) They takes long cycle Time for Processing
3) They are not true object –oriented Languages
4) They have poor type-safety
5) They have a problem of versioning
6) They are not suitable with for working upon the web

As we know that visual basic is very powerful language which is used for developing
graphical applications Visual Basic various tools which provide the ability to a user for
creating a Reusable Code. But the main Problem of visual basic is that VB has not a purely
OOP Language.
Java is purely OOP Language and this is very popular language on Web applications but
java doesn't have some powerful features like operator overloading and it also have a
problem of interacting with the another machines which have a different platforms and
java is very difficult to learn and Execute.
So that Microsoft are comes with the new ideas those are based on web applications which
integrates with Existing Systems which is known as c# language.

Contents
 Evolution of C#
 Features of C# Language
 Difference Between C# and C++
 Difference between C# and Java

Evolution of C#
We know that internet is growing day by day and demands of users are increased day by
day. and internet also have some problems like we can open only a one site at a time and
information which is Retrieved from the web is only Read-able and internet contains many
information which doesn't co-operate with the platforms so that Microsoft Chairman Bill
gates wanted to develop a Software Platform which will Remove the Limitations of internet
and provides the ability to users to get information from anywhere and anytime. So that
development work of .NET platform is being started in mid 90 and Microsoft Announced
.NET in September 2000. C# is a descendent or made from c++ which is again made from C.
Features of C# Language
Simple
As We study Earlier that C# is made from the C and C++ Language so that there are So
Many Features and The Syntax of C# are Similar to c and C++ so that a user doesn't have to
face any difficulty for Writing the Code All the Syntax of C# are same as c and C++ and C#
doesn't contains those things which are difficult for users to understand like pointers and -
> pointer operator. And in operators C# provides a Same Meaning For = and == rather for
Assigning or Checking a Value of Variable.
Consistent
We know that in c and C++ have there is a Limit For Giving a Value or we can say that in C
there is a Specific Range of Each and Every Data type and A user have to face the problem
when he crosses the limit so that C# Remove this Problem . In this C# provides a Special
data type which is called as object and this is used for storing any type of data either this
may integer ,string or any float data and a user can increase a range easily in his program
and C# Range of Variables are not Fixed but they Approximately extend up to 10 digits.
Modern
C# is also a Modern Language and it gives us an Error Message when we are using a
Variable whose value is not initialized first and provides automatic values for variables
those are also called as automatic garbage collection and also provides Exception handling
Methods.
Object –Oriented
C# is made from c# and java so that C# is also am purely OOP Language means Every
Program of C# is Written into the Classes with a Main Function Which Defines the Entry
Point for Program Execution and it also Supports Encapsulation , polymorphism and
Inheritance as a OOP Provides but C# also Doesn't Support Multiple inheritance but it
Supports Operator Overloading.
Type-Safety
C# Checks for the type Safety for all variables Means it gives values for variables if they are
not Assigning values Like All Array and Static Elements are Assigned Zero when a user cant
initialize values. This never allows a user to Casting a Variables Directly and this will
protect the Loss of data after type Conversion and Type Casting and it also has a Checked
Statement for checking the Overflow of Operations etc.
Versionable
C # Supports two new Keywords which are new and override and With the help of these
keywords any type of Version of Systems can use the Methods those are Made in C#
Language They can Simple Override the Previous Declaration of Methods.
Inter-Operability
C# Supports Inter-Operability for Making Use of Methods of C# Language . Any Method of
C-Sharp Can be Easily used by Any Language

Difference Between C# and C++


As We Know that C# Contains Many Features of C++ but there is Something Difference
Between the c++ and C# those are as Follows:-
i. After the Compilation of C# Program it Creates Executable File not an object File
ii. The First Character of Main is Always Capital instead of Smaller and this may int or
void Return type.
iii. No Need For Header Files For Using a Function
iv. Un-Initialized Variables are doesn't take Garbage Value Rather Compiler will gives
you an Error Message.
v. Data types in C# are either value type of reference Types.
vi. C# Supports goto and Label Statements
vii. For Creating an Object we have to use new Keyword
viii. C# Provides a One more Loop Which is Known as ForEach
ix. In C# We can also Create a Switch on Strings
x. For Overriding This is necessary For Methods . they might be declared as Override
Keyword
xi. C# Doesn't Supports Default Arguments
xii. We can Pass Command Line Arguments
xiii. For Checking overflow There are two Statements known as Checked and Unchecked
xiv. C# Doesn't Support Multiple Inheritance
xv. C# Doesn't Provides any Defaults For Constructors
xvi. For Abstract Methods they have no Implementation.
Difference between C# and Java
i. C# has more built in data types.
ii. C# Provides Structure but java doesn't
iii. C# Provides Operator Overloading but C# Supports
iv. Code of Java is Converted into the Bytes Code But After the Compilation of C# Code
is Directly Converted into the Executable or. Exe File is created.
v. Java uses a Static Final For Making a Variable as Final but C# uses Const Keyword
For Making a Variable as a Constant
vi. Array Declaration is Different from Java
vii. Java Provides Only vale Type Function calling because java doesn't Provides
Pointers but in C# we can Pass a Argument as a Reference by using a Reference
Keyword
viii. C# Provides another Loop Which is Called as For Each
ix. C# Supports For Passing Variable Number of Arguments Passes to a Function by
using Params Keyword.
x. In Java Member Functions are By Default Virtual Means They can be Override by
derived Class but in C# For Overriding a Function Super Class must Contains
Declaration For that Member Function as Virtual they derived Class can Override
that Function
xi. C# Uses is Operator instead of InstanceOf of Checking whether a Variable is an
Object of Class.

Literals, Variables and Data Types


C# programs are made up of components such as literals, variables, data and the like.
Contents
 Literals
 Variables
 Data Types
 Boxing and Unboxing
Literals
These are the values those are Specified in the Variables or a Literal is a value which is
used by variable A value may be either a Integer ,float or a String Variable. A literal may
represent any of the following types of values.
 Boolean Literals
 Integer Literals
 Real Literals
 Character Literals
 String Literals
 Null Literals
Boolean Literals
There are two boolean literal values: true and false. The type of a boolean-literal is bool.

Integer Literals
Integer Constants refers to a Sequence of digits which Includes only negative or positive
Values and many other things those are as follows
1. An Integer Constant must have at Least one Digit
2. it must not have a Decimal value
3. it could be either positive or Negative
4. if no sign is Specified then it should be treated as Positive
5. No Spaces and Commas are allowed in Name
Real Literals
1. A Real Constant must have at Least one Digit
2. it must have a Decimal value
3. it could be either positive or Negative
4. if no sign is Specified then it should be treated as Positive
5. No Spaces and Commas are allowed in Name
Like 251, 234.890 etc are Real Constants
In The Exponential Form of Representation the Real Constant is Represented in the two
Parts The part before appearing e is called mantissa whereas the part following e is called
Exponent.
1. In Real Constant The Mantissa and Exponent Part should be Separated by letter e
2. The Mantissa Part have may have either positive or Negative Sign
3. Default Sign is Positive
Character Literals

A Character is Single Alphabet a single digit or a Single Symbol that is enclosed within
Single inverted commas.
Like 'S' ,'1' etc are Single Character Constants
String Literals

A String Literal May be a Name or A Sequence of Characters those are written in the
double quotes and The String May Contains either digits , characters ,or any Special
Symbols.
"Hello C#"
Null Literals

null-literal
null

The type of a null-literal is the null type.


Variables
A variable is used for storing a value either a number or a character and a variable also
vary its value means it may change his value Variables are used for given names to
locations in the Memory of Computer where the different constants are stored. These
locations contain Integer , Real or Character Constants.
For example
int a;
float f;
char ch;
Data Types
Every variable has a data type which denotes the type of data which a variable will hold
There are many built in data types in data types those are called as Primitives data types or
built in data types and there are Also Some data types those are defined by user defined
types which are also called as Non-Primitives data types The data types in C# are of two
types:
1) Value Types
2) Reference: Types

Value Types
Values types are also called as Fixed Length data types which stores data on the Stack and a
when a Value data type is used only the value of a Variable is Copied by another variable
and not the Actual Address will be Passed to a variable Value Types Contains all the
Primitives data types and user defined data types Like Numeric , floating and Boolean data
types
C# .Net Framework Bytes
Signed? Possible Values
Type (System) type Occupied
Sbyte System.Sbyte Yes 1 -128 to 127
Short System.Int16 Yes 2 -32768 to 32767
Int System.Int32 Yes 4 -2147483648 to 2147483647
Long System.Int64 Yes 8 -9223372036854775808 to
9223372036854775807
Byte System.Byte No 1 -0 to 255
Ushort System.Uint16 No 2 -0 to 65535
Uint System.UInt32 No 4 -0 to 4294967295
Ulong System.Uint64 No 8 -0 to 18446744073709551615
Float System.Single Yes 4 Approximately +-1.5 x 10-45 to +-3.4 x
1038with 7 significant figures
Double System.Double Yes 8 Approximately +-5.0 x 10-324 to +-1.7 x
10308with 15 to 16 significant figures
Decimal System.Decimal Yes 12 Approximately +-5.0 x 10-28 to +-7.9 x
1028with 28 to 29 significant figures
Char System.Char N/A 2 Any Unicode character (16 bit)
Bool System.Boolean N/A 1/2 true or false
Reference Types

Reference data types are Always Stored on the heap and when we uses heap then the
Actual Location is Copied or Same Memory Location for a Single Value Will be used and you
can also say that Reference variables are used when we wants to affect on the original
values of the variable

Boxing and Unboxing


This is the newly Concept which is Provides by C# Boxing is used when we wants to
Convert the Variable of any data type into the Object data type or When we wants to Make
a Simple Variable as an object Variable and Unboxing is the Process when we wants to
Converts back an Object Variable into a Specific Variable For Boxing as we convert a integer
into a Float , we can Convert a variable into an object data type but when we wants to
Convert Object into Specific data type then we have to use Explicit Conversion or we have
to Convert the Value by Putting Name of data type in which we wants to Convert

Boxing Coversions

A boxing conversion permits any value-type to be implicitly converted to the type object
or to any interface-type implemented by the value-type. The boxing class would be
declared as follows:
//Boxing an Integer Variable
using System;
class Test
{
public static void Main()
{
int i = 123;
Object o = i; // Implicit boxing
i = 456; // change the contents of i

Console.WriteLine("The Value-Type Value={0}"i);


Console.WriteLine("The Object-Type Value={0}"o);
}
}

Output
The Value-Type value=456
The Object-Type Value=123
Unboxing Coversions

An unboxing conversion permits an explicit conversion from type object to any value-
type from or from any interface-type to any value-type that implements the interface-type
//Unboxing Conversion

using System;
public class unboxing
{
public static void Main()
{
int i = 123; // Boxing
Object o = i;
//Reference to incompatible Object produces invaliedcastException
try
{
int j = (short)o;
Console.WriteLine("Unboxing Ok");
}
catch(InvalidCastException e)
{
Console.WriteLine("{0}Error:Incorrect Unboxing",e);
}
}
}

Overview of C#

C# Provides us Making two Types of Programs either Executable Programs or either For
another Applications The Programs which contains Main Method are called as Standalone
Programs and they may used by another Applications. We know that C# is a Pure Object –
Oriented Language so that Every Program of C# is Written into the Classes A Simple
Program of C# is as Follows:-

Class abc
{
Public static void Main()
{
System.Console.WriteLine("Welcome C-Sharp");
}
}

1) We know C# is Purely OOP Language So that Every Program of C# Must be Written into
the Classes For this Class is Keyword and abc is name of Class

The Main Line


Public static void Main() is the main Line of the C-Sharp program

Public
Here Public is a Keyword which declares main method is public or unprotected so that it
will be Accessible to all classes and main can be Accessed from Outside Means data which is
Declared in the Main Can be Called from outside the Program

Static
Static is used for Describing that Method is Called without Creating any Object of Class
and this is directly Accessed and This Specifies the Main Entry Point For Execution For
Compiler . A Compiler will understand that this is the Only One Execution Point For
Executing the Statements

Void
Void means The Main Function will never Return a Value or it will Simply Prints the text
on the Screen

Contents
 Namespaces
 System.Console.WriteLine or Output Line
 Adding Comments
 Command Line Arguments
 Multiple Main Methods
 Programming Style

Namespaces
In C# System is the namespace in which all the Classes of C# are Located or you can
Name Space is Package Which Contains Collection of Classes and their Associated Methods
For Using Any Method From Any Class we have to Specify the name of Class and with the
Help of dot . Operator we can call any Method of Class But This is very Big Problem for a
user to Write a Same Line Again and Again or This is very difficult for a user to Write a Long
Name So for This Reason a user can Give am Alias or a Short Name to a Name Space Name
But For doing this Thing using directive Must be Used along with the name of the Name
Space Like This
namespace ProjectOne
{
using System
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.WinForms;
using System.Data;
}
System.Console.WriteLine or Output Line
This Line is Similar to printf in C and Cout in C++ For Displaying the Results on the
Screen at the Time of Execution in this Console is the name of class which is Located in the
System Namespace and WriteLine is the Name of Method which is Stored in Console Class
and WriteLine Always Creates or Append a New Line After Executing a Statement.

Once Installed C# on your System we can create a Program of C# in any drive and from
any where we can call a C# Program and For Compiling a C-Sharp Program we have to use
the C# Compiler Which is Knows as CSC or Simply C# Compiler and After the Compilation
this will create an Executable File not any Object file and we can Execute that File Directly
by just giving the name of File.
Adding Comments
Comments are used for only user displaying an idea for other users how the Processing
instructions will be Executed or what's the Meaning of Statements So for This A user can
give Comments for describing his Program But Always Remember Comment Lines are
never to be Executed and For Giving a Comment to a Line A user can use // for a Single Line
Comment and / * , */ for Multiple Lines as we do in other Languages.

//Single Line Comment


/* Multiple Line Comment */
Command Line Arguments
There is Situation . when output of a program is depend on input of another program So
for providing the input , C# provides us Command line Arguments These are the
parameters those are provided at Run Time or when we Interpret C# program for
Execution But Always Remember these are Always String by default C# also provide us
Length Method which is built in Method for calculating the Length of Arguments those are
supplied at the Time of Execution . Any thing which is Supplied in Command Line is given in
the String so we have to Convert the Strings into Number if we wants to use Numeric
Values For Converting String into Numbers we have to use int.Parse Method.
using System;
class Hello
{
public static void Main(string [] args)
{
for(int i = 0; i < args.Length; i++)
Console.WriteLine(Arg{0}",args[i]);
}
}
Multiple Main Methods
Generally there are Only one Main Method in Programming Languages This will Create a
big Problem For a user to store his Programs in different-2 Files So that C# Solve this
Problem and this provides us the Facility for a user to use Multiple Main Methods or in a
Single Program a user can Store Multiple Programs in a Single Programs or in a Single
Programs Multiple Main Methods are there so for this a user might decide which program
he wants to be Execute and at the Time of Compilation he can Specify the Name of Class or
Name of Class which A Main Method Resides and then that Program will be Executed.

//Multiple Main Methods


using System;
class A
{
public static void Main()
{
Console.WriteLine("First Class");
}
}
class B
{
public static void Main()
{
Console.WriteLine("Second Class");
}
}
class C
{
public static void Main()
{
Console.WriteLine("Third Class");
}
}

Compile=> If A Class -> csc A.cs/main:A


Run=> A
If B Class-> csc A.cs/main:b
A
if C Class-> csc A.cs/main:c
A
Programming Style
C# is a free Form Programming Language which allows a user to write his Code in a Free
Form Means he Can Write a Single Line into Multiple Lines but Always Remember a user
cant Break the Name Class from a Namespace he can only break only quotes ,dot and Open
Parenthesis etc.
Like this

System.Console.WriteLine(" Hello " );

Program: For Writing any Instruction a user have to write a Program. A Program Contains
Many Statements Which Further Contains Variables, Constants, Operator etc. Special
Characters etc . Generally a Program Contains

Operators and Expressions

One reason for the power of C# is its wide range of useful operators. An operator is a
function which is applied to values to give a result. You should be familiar with operators
such as +,-,/. Arithmetic operators are the most common. Others operators are used for
comparison of values, combination of logical states, and manipultation of individual binary
digits.
Contents
 What is Operators
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment/Decrement Operators
 Conditional Operators or Ternary Operators
 Bitwise Operators
 Special Operators
2.1 What is Operators
As C# rich in data types, same as C# is rich in Operator. From every Operator, C#-
expression can be defined. By using some Operators we can solve or compute a formula, we
can compare two expresssions or variable value, or can create logical relationship between
compound statement, can solve a conditinal expresssion, can do low-level programming
and special types of Operators.
Mainly Operators are used to operate two or more than two operands depending upon
their processing and given conditions. The relationship of operator with the operands is
shown as in the below common statement:
Operand1 Operator Operand2
Or
Operand1 Operator Operand2 Operator Operand3
Here Operand1, Operands, Operand3 may be variable, a constand or an expression etc.
There are mainly eight operators used in C-Language.

The list of various operators as shown above are described in details as:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment/Decrement Operators
 Conditional Operators or Ternary Operators
 Bitwise Operators
 Special Operators
Arithmetic Operators
Arithmetic Operators are used for arithmetic operations like Addition Subraction,
Multiplication, Division etc. Mostly arithmetic operators are used in the all the computer
languages. There are five arithmetic operators used in C#-language. These all are given in
the table below
Operator Meaning
* multiplication
/ division
% modulus (remainder after division)
+ addition
- subtraction

For example, Suppose a & b are two variables, then arithmetic operators used for different
operations as:
a*b (multiplication of a with b)
a/b (division of a by b)
a%b (to find module of a with b)
a+b (addition of a and b)
a-b (subtraction of b from a)

Relational Operators
These operators are used to create logical relationship between two operands.
Relational operators are used for comparison purpose. The expression having two
operands and one relational is called Relational Expression. There are mainly six relational
operators used in the C#-Language. These all are given in the table as:
Operator Meaning
< less than
<= less than and equal to
> greater than
>= greater than and equal to
== equal to
!= not equal to
For example, Suppose a & b are two variables, If a=5 and b=2 are two integer type variables
then some relational expressions using the relational operations are:
a<b< td=""></b<> True
a<=b True
a>b false
a>=b false
a==b false
a!=b True

Logical Operators
Logical operators are used for logical operations. These operations are used for
compound relational expressions or logical expressions. When more than one reltional
expression occur in a C# expression using logical operators, then such type of expressions
are called Compound Relational Expressions or Logical expression. These are used in
decision-making statement adn some looping statement like if,switch, do while, while and
for etc. These statement have either True (1) bracnh or false (0) branch. There are mainly
three logical operators used in C# language as in the table below :
Operator Meaning Priority
Logical NOT
! Highest
(Not process the condition)
Logical OR
|| Intermediate
(Process any one of the conditions.)
Logical AND
&& Lowest
(Process two or more than two relational expressions)

Assignment Operators
Assignment operators are used for assigning an expression or value (constant) to a
variable. Assignment operators are further subdivided into two types:

a) Simple Assignment Operator


b) Short hand Assignment Operator
OR
Arithmetic Assignment Operator

The general syntax :

v= constant value or variable or expression;


Where v is the variable and expression be any arithmetic expression. for example :
sum = 0;
i=1
a = b;

Shorthand Assignment
R i+= 1;
p*= a-b;
l/=1;
Conditional Operators
Conditional Operators are aslo called ? : operators or ternary operator. These operators
are used instead of block if statement. The general syntax of conditional operator are as :
exp1 ? exp2 : exp3;

for example

c =(a>b) ? a-b :a + b;
Increment/Decrement Operators:
These operators are also sometimes called special operators or unary special operators.
Another name or Increment/Decrement Operators is Counter Operator. These are two as:
++ (increment operator) and -- (decrement operator). Increment operator are used for
incrementing the value one by one. Similarly decrement operator are used for
decrementing the value one by one. These are further sub-divided into two categories:

a) Prefix Increment / Decrement Operator


b) Postfix Increment / Decrement Operator

a) Prefix Operator:
In the Prefix increment operator, first of all value will be increment and the
incremented value will be assigned to a variable. Similarly in the prefix decrement operator
first of all value will be decrement and then decremented value be assigned to the variabl.
The general way is represendted as:

++v;
--v;

b) Postfix Operator:
In the postfix increment operator, first of all value will be assigned to a variable and
then it will be incremented. Similarly in the postfix decrement operator first of all value will
be assigned and then it will be decremented. The general way is represendted as:

v++;
v--;

Bitwise Operators:
These are special operators for low level programming. These operators are used for
the manipulation of binary data (bits). Ther are six types of Bitwise Operator. The table for
Bitwise Operators is as:
Operator Meaning
& Bitwise AND
| (pipe symbol) Bitwise OR
^ Bitwise exclusive OR
<< Bitwise left
>> Bitwise right
~ (tilde) Bitwise NOT (complement operator)

Special Operators:
These are used for special purposes in C#-language. These operators are used in
pointers, structures and unions etc. Some types of special operators are as:
1. Unary Operator
2. Comma Operator
3. Sizeof Operator
4. Type Operator
5. Pointer Operator
6. Member Selection Operator

Branching and Looping

We know that Instruction those are written in C# Language are Executed in Sequence wise or
Step Wise as they are Written in Program. or these are Executed in Sequence Order. Decision
Making statements are used when we wants to execute the statements as according to the user
needs. A User can Change the Sequence of the Statements for Execution. Many Times we Wants to
Execute the Set of Instructions to be Executed in one Situation and other Statements in other
Situations For Executing the Statements in Specific Situation there are Some Decision Making
Statements or Decision or Control Statements those are provided by the java Language. In The
Decision First a Condition is checked if it is true then it Executes the next Instruction otherwise it
Executes other Statements.

There are three decision making statements :-


1. if
2. Switch Statement
3. The Conditional or ternary Operator
Contents
 Branching Statement
 Looping Statement
 Jumping Statement

Branching Statement
if statement

The Keyword if tells the compiler what follows The Condition Following the Keyword if
is always enclosed within a pair or Parentheses if The Condition id True Then the
Statements is Executed if the Condition is not true then the Statement is not Executed For
Checking a condition Relational Operators are Used Like > ,< ,==, >=,<= etc. The if statement
is widely used for checking a particular condition Suppose you want to check the condition
and then execute the condition if your condition is met.
for ex:
if(a>b)
then print a is greater then here we first check the condition
that either a is greater than b if yes then execute the condition
//if program
using System;
class abc
{
public static void Main()
{
int a;
a = 1;
if(a==1)
{
Console.WriteLine("C# is Sharpe");
}
}
}
if-else

The if Statement is used for Executing a Single Statement or a Group of Statements When
the Condition Following is true . It does nothing when the Condition is False , For Executing
the group of Statements either a Condition is False we uses else The if-else is similar to if
but the difference is that is also provides us the alternative to execute the other statement
if a condition is not true for ex:

if(a>b)
print a
else
print b
Here if first checks the condition either the a is greater than b if yes then it will print a
suppose if a is not greater than b then it will be print b because we specify the b in the else
statement.
//if-else program
using System;
class abc
{
public static void Main()
{
int a;
a = 1;
if(a==1)
{
Console.WriteLine("Yes Equal to One");
}
else
{
Console.WriteLine("Not Equal to One");
}
}
}
if-else if

The if-else if is similar to the if-else but here the first if is used for checking a condition
and the other else if is used for checking a one more condition suppose if we wants to check
the two or more conditions then we can use the if-else if.
//else-if program
using System;
class abc
{
public static void Main()
{
int a,b,c;
String s1,s2,s3;

s1=Console.ReadLine();
a = int.Parse(s1);
Console.WriteLine("Enter a Number="+a);

s2=Console.ReadLine();
b = int.Parse(s2);
Console.WriteLine("Enter a Number="+b);

s3=Console.ReadLine();
c = int.Parse(s3);
Console.WriteLine("Enter a Number="+c);

if(a > b && a > c)


{
Console.WriteLine("A is Greatest");
}
else if(b > a && b > c)
{
Console.WriteLine("B is Greatest");
}
else if(c > a && c > b)
{
Console.WriteLine("C is Greatest");
}
else
{
Console.WriteLine("All are Equals");
}
}
}
Nested if ....else statement
When an if statement occurs within another if statement, then such type of is called
nested if statement.
//else-if program
using System;
class abc
{
public static void Main()
{
int a,b,c;
String s1,s2,s3;

s1=Console.ReadLine();
a = int.Parse(s1);
Console.WriteLine("Enter a Number="+a);

s2=Console.ReadLine();
b = int.Parse(s2);
Console.WriteLine("Enter a Number="+b);

s3=Console.ReadLine();
c = int.Parse(s3);
Console.WriteLine("Enter a Number="+c);

if(a > b)
{
if(a > c)
{
Console.WriteLine("A is Greatest");
}
}
if(b > a)
{
if(b > c)
{
Console.WriteLine("B is Greatest");
}
}
if(c > a)
{
if(c > b)
{
Console.WriteLine("C is Greatest");
}
}
}
}
The ? : Operator

This operator is an assignment operator that selects one of the two values depending on
the truth value of given condition. consider the following code snippet.
A = condition ? value1 : value2;

The value1 is assigned to the variable a in case the condition is true otherwise value2 is
assigned to the variable a.
//The ? : Operator program
using System;
class abc
{
public static void Main()
{
int x,a,b;
a = 100;
b = 200;

x = (a > b) ? a : b;

Console.WriteLine("Largest No: "+ x);


}
}
Switch Statement
This Statement is Similar to if –else but it uses matching operations rather than checking
a condition if we Wants to Check Many Conditions then the Program will very Complex So
in that Situation We Will use Switch Statement Switch Statement Uses Many Cases rather
and it matches the value with Case where it Matches it will Execute the Statement But
There is Very Necessary to Stop the Execution of Each Case So that it Doesn't Execute Next
Case So that for this Purpose we have to put the break Statement after Ending of an Each
Case We Know if uses Else Statement if Condition is False or All Conditions are False The
Code of Else Statement is Executed if Code of all if statements is false So that in Switch
Default is used when all Cases are not Matched In other Languages like c and C++ we can
Match Only the Integer or a Character value but in the C# We can also a String in the Switch
Statement.

//The Switch program


/* Main Menu
1. Red
2. Green
3. Yellow
Enter Your Choice (1-3)
*/
using System;
class abc
{
public static void Main()
{
int ch;

Console.WriteLine("Main Menu");
Console.WriteLine("1. Red");
Console.WriteLine("2. Green");
Console.WriteLine("3. Yellow");

Console.WriteLine("Enter Your Choice (1-3);

ch.Int32.Parse(Console.ReadLine());

switch(ch)
{
case 1:
{
Console.WriteLine("Red");
break;
}

case 2:
{
Console.WriteLine("Green");
break;
}
case 3:
{
Console.WriteLine("Yellow");
break;
}
default:
{
Console.WriteLine("Wrong");
break;
}
}
}
}
Looping Statement
A Computer is used for performing many Repetitive types of tasks The Process of
Repeatedly performing tasks is known as looping The Statements in the block may be
Executed any number of times from Zero to Up to the Condition is True The Loop is that in
which a task is repeated until the condition is true or we can say in the loop will Executes
all the statements are until the given condition is not to be false. These are generally used
for repeating the statements. In this There is Either Entry Controlled loop or as Exit
Controlled Loop We know that before Execution of Statements all Conditions are Checked
these are Performed by Entry Controlled Loops Which First Checks Condition And in Exit
Controlled Loop it Checks Condition for Ending Loop Whether given Condition is False or
not if a Loop First Checks Condition For Execution then it is called as Entry Controlled Loop
and if a Loop Checks Condition after the Execution of Statement then they are Called as Exit
Controlled Loops.

In The loop generally there are three basic operations are performed
1) Initialization
2) Condition check
3) Increment

There are the three types of loops in the C#


1. while
2. do-while
3. for
4. foreach
All these are used for performing the repetitive tasks until the given condition is not true.
While
While Loop is Known as Entry Controlled Loop because in The while loop first we
initialize the value of variable or Starting point of Execution and then we check the
condition and if the condition is true then it will execute the statements and then after it
increments or decrements the value of a variable. But in the Will Condition is false then it
will never Executes the Statement.
//The while program
using System;
class abc
{
public static void Main()
{
int i = 1;
while (i < =10)
{
Console.WriteLine(i);
i++;
}
}
}
Do while
This is Also Called as Exit Controlled Loop we know that in The while loop the condition
is check before the execution of the program but if the condition is not true then it will not
execute the statements so for this purpose we use the do while loop in this first it executes
the statements and then it increments the value of a variable and then last it checks the
condition So in this either the condition is true or not it Execute the statement at least one
time.
//The do-while program
using System;
class abc
{
public static void Main()
{
int i = 1;
do
{
Console.WriteLine(i);
i++;
}
while (i < =10);
}
}
For
In This loop all the basic operations like initialization ,condition checking and
incrementing or decrementing all these are performed in only one line. this is similar to the
while loop for performing its execution but only different in its syntax.
//The for program
using System;
class abc
{
public static void Main()
{
int i;
for(i = 1; i <=10; i++)
{
Console.WriteLine(i);
}
}
}
Foreach
This is another type of Loops which is provided by C# Language this Loops works
Collection Variables Like Arrays, List and Strings or Any Command Line Arguments. For
each Loop First initialize a first Value which is Stored into the Collection Element and then
as loop do the Next Element will be Assigned to the foreach variable But Remember we do
not have to end foreach loop Explicitly by using Any Statement.
//The for program
using System;
class abc
{
public static void Main(String []args)
{
int i;
foreach(String s in args)
{
Console.WriteLine(s);
}
}
}
//The same way be achieved using the foreach
for (int i = 1; i < args.Lenth; i ++)
{
Console.WriteLine(args[i]);
}
Jumping Statement
These Statements are also Called as Jumping Statements those are used for transferring
the Control of Execution of program using break, continue etc.
Break
This statement is used for stopping the execution of the program the break statement is
used where we does t want to execute the next statements and Wherever it finds a Break
Statement then from that Compiler will not Execute Any Statement. And the Execution of
program will be halt or Stopped it doesn't Execute Any Statement after the break
Statement.
//The break program
using System;
class abc
{
public static void Main()
{
int i = 1;
while (i < =10)
{
if(i==5)
{
break;
}
Console.WriteLine(i);
i++;
}
}
}
Continue
The Continue Statements is used for executing the statements by skipping a statement
for ex if u don t want to execute any statement then we can use the continue means to skip
a particular statement and then execute the next statements. Wherever it Finds a Continue
Statement the Control Will be Transferred to another Statement But Always Remember
once the Control has been Transferred this will never come back to its Previous Statement.
//The continue program
using System;
class abc
{
public static void Main()
{
int i = 1;
while (i < =10)
{
if(i==5)
{
continue;
}
Console.WriteLine(i);
i++;
}
}
}
Goto
Goto Statement is used for transferring the Execution to another Statements to a Specific
Location and Location is Explicitly defined by user and that Location must have a Specific
Name so that when a use wants to send to that Location he must have to Specify the Name
along with goto . Name with Goto have any valid Name and Must be defined by using Colon
(: )

//The goto program


using System;
class abc
{
public static void Main()
{
int i = 1;
for(i = 0; i < 12; i++)
{
if(i==10)
{
goto gurmail;
}
else
{
Console.WriteLine(i);
}
gurmail:
Console.WriteLine("Hello I'm Goto Statement!!!");
}
}
}

Inheritance

Inheritance means using the Pre-defined Code. This is very Main Feature of OOP With the
advantage of Inheritance we can use any code that is previously created With the help of
inheritance we uses the code that is previously Defined but always Remember We are only using
that code but not Changing that code With the Advent of inheritance we able to use pre-defined
code and also able to add new code. All the pre-defined code is reside into the form of classes if we
wants to use that code then we have to inherit or extend that class The Class that is Pre-defined is
called as Base or super Class and the class which uses that code is called as derived or sub class
There many types of Inheritance provided by C# But Multiple Inheritance is not Provided by C#.
Various types of inheritance provided by C# is as follows:
 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
Contents
 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Hiding through Inheritance
 Inheritance and Constructors
 Containment Class
 Method Overriding
Hiding through Inheritance
Name hiding through inheritance occurs when classes or structs redeclare names that
were inherited from base classes. The type of name hiding takes one of the following forms.
1. A constant, field, property, event, or type introduced in a class or struct hides all
base class members with the same name.
2. A method introduced in a class or struct hides all non-method base class members
with the same name, and all base class methods with the same signature.
3. An indexer introuced in a class or struct hides all base class indexers with the same
signature (parameter count and types).
Contrary to hiding a name from an outer scope, hiding an accessible name from an
inherited scope causes a warning to be reported. In the example
/* Hiding through Inheritance */
using System;
class a
{
public void show()
{
Console.WriteLine("Base Class");
}
}
class b:a
{
public new void show()
{
Console.WriteLine("Derived Method");
}
}

class c
{
public static void Main()
{
b obj = new b();
obj.show();
}
}
Inheritance and Constructors
The constructors and destructors are not inherited to a derived class from a Base class.
However when we crate an object of the derived class, the derived class constructor
implicitly call the base default constructor. The following prgram show this.
/* Inheritance and Constructors */
using System;
class Base
{
public Base()
{
Console.WriteLine("Base Class default Constructor");
}
}
class Derived:Base
{
public Derived()
{
Console.WriteLine("Derived Class default Constructor");
}
}

class MyClient
{
public static void Main()
{
Derived obj = new Derived();
}
}
Containment Class
With the Advent of C# we can Also Develop Also Some Another Form of Inheritance
which is also known as the m Containment . Inheritance is Called as Containment when we
are Declaring the Object of a class into another Class Then They have a Relationship Like
house has a Room and Car has a Stereo etc.
Method Overriding
In inheritance a user may have to face Problem about using the Same name Method in
both the Classes like in Base and Derived Classes there is Same Name of a Class so that if we
wants to Define a Method which is Similar to base class in a derived Class then we have to
use two Keywords as Virtual and Override.

The Method which is declared as Virtual in a base class , can only be Override by derived
Class, if in the Derived Class uses Override Keyword along with the Name of Method which
we wants to Defined Again. And if you wants to Access the Method of Base Class then we
have to use the Base.
Operator Overloading

All unary and binary operators have pre-defined semantic implementations, that are
automatically available in any expressions. In addition to this pre-defined implementations, user
defined implementations can also be introduced in C#. The mechanism of giving a special meaning
to a standard C# operator with respect to a user defined data type such as classes or structures is
known as Operator Overloading.
Contents
 Overloadable Operators
 Need for Operator Overloading
 Defining Operator Overloading
 Overloading Unary Operators
 Overloading Binary Operators
 Overloading Comparison Operators
 Rules of Operator Overloading
Overloadable Operators
Operators can be overloaded to give them new additional semantic meaning. However,
some of the C# operators cannot be overloaded at all. The following table shows the
operators and their overloadability in C#.
Operators Overloadability
+,-,*,/,%,&,|,<<,>> All C# binary operators can be overloaded.
+,-,!,~,++,--,true,false All C# unary operators can be overloaded.
All relational operators can be overloaded, but only
==,!=,<,>,<==,>==
as pairs.
&&,|| Can't be overloaded
(), (Conversion operator) Can't be overloaded
These compound assignment operators can be
overloaded. But in C#, these operators are
+=,-=,*=,/=,%=
automatically overloaded when the respective binary
operator is overloaded
=,.,?,->, new, is , as, sizeof Can't be overloaded

Need for Operator Overloading


Object oriented programming must exhibit polymorphism. Operator overloading is one
such mechanism through which C# achieves polymorphism, though other mechanisms for
polymorphism also exist.

Consider, for example , that the + operator is defined normally to add two numeric values
irrespective of their type. In this sense + operator is overloaded by definition.
Thus,

int a = 20 + 30;
is a valid operation.

Moreover, if a programmer wishes to use the same operator + to mean adding


(concatenation) two strings, the + operation must be overloaded accordingly. But for
operator overloading feature it would not be possible to ascertain polymorphism in C#. By
overloading + appropriatly, we can use + operator in the following manner.

String = "ABC" + "XYZ";


Defining Operator Overloading
In C#, a special function called operator function is used for overloading purpose. These
special fucntion or method must be public and static. They can take only value arguments.
The ref and out parameters are not allowed as arguments to operator functions. The
general form of an operator function is as follows.

public static return_type operator op (argument list)

Where the op is the operator to be overloaded and operator is the required keyword. For
overloading the unary operators, there is only one argument and for overloading a binary
operator there are two arguments. Remember that at least one of the arguments must be
user-defined type such as class or struct type.
Overloading Unary Operators
The general form of operator function for unary operators is as follows.

public static return_type operator op (Type t) { // Statements }

Where Type must be a class or struct. The return_type can be any type except void for
unary operators like +,~,! and dot (.). but the return_type must be the type of Type for ++
and remember that the true and false operators can be overloaded only as pairs. The
compliation errors occurs if a class declares one of these operators without declaring the
other.

The following program overloads the unary (-) operator inside the Base class.
/* Unary Operator Overloading */
using System;
class Base
{
private int x;
private int y;
public Base(int i, int j)
{
x = i;
y = j;
}
public void show()
{
Console.WriteLine("{0}{1}",x,y);
}
public static Base operator - (Base ob)
{
Base t = new Base();
t.x = -b.x;
t.y = -b.y;
return t;
}
}

class UnaryOpeOverloading
{
public static void Main()
{
Base obj = new Base(10,20); //display 10 and 20
obj.show();
Base obj2 = new Base(); //display 0 and 0
obj2.show();
obj2 = -obj;
obj2.show(); //display -10 and -20
}
}
Overloading Binary Operators
An overloaded binary operator must take two arguments and at least one of them must
be of the type class or struct, in which the operation in defined. But overloaded binary
operators can return any value except the type void. The general form of an overloaded
binary operator is as follows.

public static return_type operator op (Type t1, Type2 t2) { //Statement }

A concrete example is given below. This program overloads plus (+) operator to mean
adding two complex numbers defined by class Base.
/* Binary Operator Overloading */
using System;
class Base
{
private int x;
private int y;
public Base(int i, int j)
{
x = i;
y = j;
}
public void show()
{
Console.WriteLine("{0}{1}",x,y);
}
public static Base operator + (Base ob, Base ob2)
{
Base t = new Base();
t.x = ob.x + ob2.x;
t.y = ob.y + ob2.y;
return t;
}
}

class BinaryOpeOverloading
{
public static void Main()
{
Base obj = new Base(10,20); //display 10 and 20
obj.show();

Base obj1 = new Base(20,30); //display 20 and 30


obj1.show();

Base obj2 = new Base();


obj2 = obj + obj1; // + overload used
obj2.show(); //display 30 and 50
}
}
Overloading Comparison Operators
The binary operators such as ==,!=,< , > <=,>= can be overloaded only as pairs.
Remember that when a binary arithmetic opeartor is overload, corresponding assignment
operators also get overloaded automatically. For example if we overloaed + operator, it
implicitly overloads the += operator also.
/* Comparison Operator Overloading */
using System;
class Over
{
public int a,b;
public Over
{
a = 10;
b = 20;
}

public Over(int x, int y)


{
a = x;
b = y;
}

public void Show()


{
Console.WriteLine("A = "+a);
Console.WriteLine("B = "+b);
}

public static bool operator > (Over o, Over o1)


{
if(o.a > o1.a && o.b > o1.b)
{
return true;
}
else
{
return false;
}
}

public static bool operator > (Over o, Over o1)


{
if(o.a < o1.a && o.b < o1.b)
{
return true;
}
else
{
return false;
}
}
}

class ComparisonOpeOverloading
{
public static void Main()
{
Over ob = new Over();
ob.Show();

Over obj1 = new Over(100,200);


obj.Show();

if(obj > obj1)


{
Console.WriteLine("First Object is Greater");
}
else
{
Console.WriteLine("Second Object is Greater");
}
}
}
Rules of Operator Overloading
While Overloading an operator, the following rules must be kept in mind.
1. The user defined operator declarations can't modify the syntax, precedence or
associativity of an operator. For example, a + operator is always a binary operator
having a predefined precedence and an associativity of left to right.
2. User defined operator implementations are given preference over prefefined
implementations.
3. Operator overload methods can't return void.
4. The operator overload methods can be overloaded just like any other methods in
C#. The overloaded methods shoult differ in their type of arguments and/or number
of arguments and/or order of arguments. Remember that in this case also the return
type is not considered as part of the method signature.
Managing Error and Exceptions

Trapping and handling of runtime errors is one of the most crucial tasks ahead of any
programmer. As a developer, you sometimes seem to spend more time checking for errors and
handling thme than you do on the core logic of the actual program. You can address this issue by
using system exceptions that are designed for the purpose of handling errors.
Types of Errors
An error is a conditon that is not intended in the system. Errors can be of many types and may
creep in any phase of system development. Some of the error types are mentioned below:
 Syntax error
 Semantic error
 Logical error
 Compile-time error
 Run-time error
Contents
 Exceptions
 Syntax of Exception Handling Code
 Multiple Catch Statement
 Using Finally Statement
 Throwing Our Own Exceptions
Exceptions
An Exception is an error condition or unexpected behavior encountered by an executing
program during runtime. Errors can happen at almost any time during the compilation or
execution of a program. We can detect and deal with these errors using Exception
Handling. Exception handling is an in built mechanism in .NET freamework to detect and
handle run time errors. At the heart of .NET Framework is the Common Language Runtime
(CLR) which is addition to acting as a virtual machine and interpreting and executing IL
code on the fly, performs numerous other functions such as type safety checking, memory
management, garbage collection and Exception handling.
Syntax of Exception Handling Code
C# provides three keywords try, catch and finally to do exception handling. The try
encloses the statements that might throw an exception whereas catch handles an exception
if one exists. The finally can be used for doing any clean up process. The general form try-
catch-finally in C# is shown below.

try
{
// Statement which can cause an exception
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
// Any cleanup code
}

If any exception occurs inside the try block, the control transfers to the appropriate catch
block and later to the finally block.
Multiple Catch Statement
A try block can throw multiple exceptions, which can be handled by using multiple catch
block. Remember that more specialized catch block should come before a generalized one.
Otherwise the compiler will show a compilation error.
using System;
class err2
{
public static void Main()
{
int a[] = {5,10};
int b = 5;

try
{
int x = a[2] / b - a[1];
}
catch(ArithmeticException e)
{
Console.WriteLine("Division by Zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
Console.WriteLine("Array index Error");
}
catch(ArrayStoreException e)
{
Console.WriteLine("Wrong data type");
}

int y = a[1] / a[0];


Console.WriteLine("Y ="+y);
}
}
Using Finally Statement
In C#, both catch and finally blocks are optional. The try block can exist either with one
or more catch blocks or a finally block or with both catch and finally blocks.

If there is no exception occurred inside the try block, the control directly transfers to finally
block. We can say that the statements inside the finally block is executed always. Note that
it is an error to transfer control out of a finally block using break, continue, return or goto.

In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used


for this purpose. The general form of throwing an exception is as follows.

throw exception_obj;

For example the following statement throw an ArgumentException explicity.

throw new ArgumentException("Exception")


//C#: Exception Handling:
using System;
class MyClient
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception");
}
Console.WriteLine("Last Statement");
}
}
Throwing Our Own Exceptions
In C#, it is possible to create our own exception class. But Exception must be the ultimate
base class for all exceptions in C#. So the user-defined exception classes must inherit from
either Exception class or one of its standard derived classes.
using System;
class MyException:Exception
{
public MyException(String str)
{
Console.WriteLine("User Defined Exception");
}
}
class MyClient
{
public static void Main()
{
try
{
throw new MyException("Pardeep");
}
catch(Exception e)
{
Console.WriteLine("Exception Caught here " + e.ToString());
}
Console.WriteLine("Last Statement");
}
}
Delegates and Events

Delegates are reference types, which allow indirect calls to methods. A delegate instance holds
references to a number of methods. By invoking the delegate one caused all of these methods to be
called. The usefulness of delegates lies in the face that the functions, which invoke them are blind to
the underlying methods they thereby cause to run.
It can be seen that delegates are functionally rather similar to C++'s function pointers. However, it
is important to bear in mind two main differences. Firstly delegates are reference types rather than
values types. Secondly, some single of delegates can reference multiple methods.

An event in C# is a way for a class to provide notifications to clients of that class when some
interesting thing happens to an object. The most familiar use for events is in graphical user
interfaces, typically, the classes that represent controls in the interface have events that are notified
when the user does something to the control (for example, click a button).
Contents
 Using Delegates
 Multicast Delegate
 Events
 MulticastDelegate Using through Keyborad
Using Delegates
Delegates can be specified on their own in a namespace, or else can be specified within
another class. In each case, the declaration specifies a new class, which inherits
from System.MulticastDelegate.
/* Delegate */
using System;
delegate void D(int x);
class c
{
public static void show(int i)
{
Console.WriteLine("Power = "+i);
}
}
class del
{
public static void Main()
{
D obj = new D();
obj(10);
}
}
Multicast Delegate
Multicasting is a technique that allows an object call any number of functions. It is
derived from MulticastDelegate class. A new function can be added to the delegate list, the
- MulticastDelegate.Combine() - method is used. The general syntax of the same is:

MulticastDelegate.Combine(delegate1, delegate2);

Note that since + operator is overloaded, the above can also be written as :

MulticastDelegate mdel = delegate1 + delegate2;

Creating a multicast delegate variable - mdel.


Similarly, a delegate can be removed from the delegate list using
- MulticastDelegate.Remove() - method whose general syntax is:

MulticastDelegate.Remove(delegate1);
The following program show MulticastDelegate.
/* MulticastDelegate */
using System;
delegate void D();
class c
{
public static void add()
{
int a,b,c;
a = 20;
b = 10;
c = a + b;
Console.WriteLine("Sum = "+c);
}
public static void sub()
{
int a,b,c;
a = 20;
b = 10;
c = a - b;
Console.WriteLine("Subtraction = "+c);
}
}

class Muldel2
{
public static void Main()
{
D obj1 = new D(c.add);
D obj2 = new D(c.sub);
D obj3 = obj1 + obj2;
obj3();
D obj4 = obj1 - obj2;
obj4();
}
}
Events
An event is C# is a way for a class to provide notifications to clients of that class when
some interesting thing happens to an object. The most familiar use for events is in graphical
user interfaces; typically, the classes that represent controls in the interface have events
that are notified when the user does something to the control (for example, click a button).

Events, however, need not be used only for graphical interfaces. Events provide a generally
useful way for objects to signal state changes that may be useful to clients of that objects.
Events are an important building block for creating classes that can be reused in a large
number of different programs.

Events are declared using delegates. An event is a way for a class to allow clients to give it
delegates to methods that should be called when the event occurs. When the event occurs,
the delegate(s) given to it by its clients are invoked. To declare an event inside a class, first
a delegate type for event must be declared. The following program show event in C#.
/* Events */
using System;
public delegate void sum(int x, int y);
class number
{
public event sum sevent; //Event made using delegate
public void addition()
{
if(sevent!=null)
{
sevent(100,300);
}
}
}

class even
{
public static void Main()
{
number obj = new number();
obj.sevent t = new sum(add);
obj.addition();
}

public static void add(int x, int y)


{
Console.WriteLine("Sum = "+(x + y));
}
}
MulticastDelegate Using through Keyborad
/* Delegate */
using System;
delegate void D();
class c
{
public static void Sum()
{
int a,b,c;
Console.WriteLine("Enter the Two Numbers for Sum");
Console.WriteLine("Enter the Value of A");
a = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter the Value of B");
b = Int32.Parse(Console.ReadLine());

c = a + b;
Console.WriteLine("Sum = "+c);
}

public static void Sub()


{
int a,b,c;
Console.WriteLine("Enter the Two Numbers for Subtraction");
Console.WriteLine("Enter the Value of A");
a = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter the Value of B");
b = Int32.Parse(Console.ReadLine());

c = a - b;
Console.WriteLine("Subtraction = "+c);
}

public static void Mul()


{
int a,b,c;
Console.WriteLine("Enter the Two Numbers for Multiplication");
Console.WriteLine("Enter the Value of A");
a = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter the Value of B");
b = Int32.Parse(Console.ReadLine());

c = a * b;
Console.WriteLine("Multiplication = "+c);
}

public static void Div()


{
int a,b,c;
Console.WriteLine("Enter the Two Numbers for Division");
Console.WriteLine("Enter the Value of A");
a = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter the Value of B");
b = Int32.Parse(Console.ReadLine());

c = a / b;
Console.WriteLine("Division = "+c);
}
}
class del4
{
public static void Main()
{
D obj1 = new D(c.Sum);
D obj2 = new D(c.Sub);
D obj3 = new D(c.Mul);
D obj4 = new D(c.Div);

obj1();
obj2();
obj3();
obj4();
}
}
Managing Console I/O Operations

Console is the set of devices throught which a user communicates with a system using interactive
set of commands. GUI is not considered as console in this respect. The primary input device in most
of the computer systems is a keyboard and the primary output is the monitor. The pair forms the
user's console in most of the caseds
Contents
 The Console Class
 Managing Console I/O Operations
 Console.OpenStandardInput Method()
 Console.OpenStandardOutput Method()
 Console.Read Method()
 Console.ReadLine Method()
 Console.Write Method(Boolean)
 Console.Write Method(String)
The Console Class
To allow console input/output operations, C# provides, C# provides a console class. The
Console class provides basic input and output support for applications that read from and
write characters to the console. The standard input, output, and error streams are
represented by properties, and are automatically associated with the console when the
application starts. Application can redirected these properties to other streams; for
example, streams associated with fies instead of the console.

By default, the read methods in console class use the standard input stream (keyboard) and
the write methods use the standard output (monitor) stream.

The write methods support writing data with or without automatically appending carriage
return and linefeed characters. This enables the writing of string, formatted strings, arrays
of characters, instances of primitive types, and arbitrary objects without first having to
convert them to strings.

The following example demonstrates the use of basic Console input and output functions.
/* Console Input/Ouput */
using System;
class ConsoleTest
{
public static void Main()
{
Console.Write("Hello");
Console.WriteLine("World");
Console.Write("What is Your Name");
String name = Console.ReadLine();
Console.Write("Hello, ");
Console.Write(name);
Console.WriteLine(" ! ");
}
}
Managing Console I/O Operations
Console input/ouput operations are carried out by the Console class which is inside
system namespace and is stored in Mscorlib (in Mscorlib.dll) assembly.
Data from the console is read from the standard input stream; normal data to the console is
written to the standard output stream; and error data to the console is written to the
standard error output stream. These streams are automatically associated with the console
when your application start, and are presented to you as the In, Out, and Error properties.

By default, the value of the In property is a System.IO.TextReader, while the values of


the Out and Error properties are System.IO.TextWriter objects. However, you can
associate these properties with streams that do not represent the console. This class
synchronized TextReader and TextWriter instances. Multiple threads can concurrently
read from or write to an instance of this type.
Console.OpenStandardInput Method()
This method acquires the standard input stream. The code given below shows this. This
method can be used to reacquire the standard input stream after it has been changed by
the SetIn method. Consider the following code snippet for illustration.
The following code sample illustrates the user of OpenStandardInput:

public class Decoder


{
public static void Main()
{
Stream inputStream = Console.OpenStandardInput();
byte [] bytes = new byte[100];
Console.WriteLine("To decode, type or paste the UTF7 encoded string and press enter:");
Console.WriteLine("(Example: \"M+APw-nchen ist wundervoll\")");
int outputLength = inputStream.Read(bytes, 0 ,100);
char [] chars = Encoding.UTF7.GetChars(bytes, 0 , outputLenght);
Console.WriteLine("Decoded String:");
Console.WriteLine(new string(chars));
}
}

Console.OpenStandardOutput Method()
The method acquires the standard output stream. This method can be used to reqcquire
the standard output stream after it has been changed by the SetOut method. Consider the
following code snippet for illustration.
public class InsertTabs
{
private const int tabSize = 4;
private const string usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
public static int Main(String[] args)
{
StreamWriter writer = null;

if (args.Length < 2)
{
Console.WriteLine(usageTextt);
return 1;
}
try
{
write = new StramWriter(args[1]);
Console.SetOut(writer);
Console.SetIn(new StreamReader(args[0]));
}
catch(IOException e)
{
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
errorWriter.WriteLine(usageText);
return 1;
}
string line;
while((line = Console.ReadLine())!= null)
{
string newLine = line.Replace(("").PadRight(tabSize,'),"\t");
Console.WriteLine(newLine);
}
writer.Close();
//Recover the standard output stream so that a
// Completion message can be displayed.
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine("INSERTTABS has completed the processing of (0).", args[0]);
return 0;
}
}
Console.Read Method()
This method reads the next character from the standard input stream. It returns the next
character from the input stream, or negative one (-1) if no more characters are available.
This method will not return until the read operation is terminated; for example by the user
pressing the enter key. If data is available, the input stream contains what the user entered,
suffixed with the environment dependent newline character. Consider the following for
illustration.

int i;
char c;
while(true)
{
i = Console.Read();
if (i == 1)
break;
c = (char) l;
Console.WriteLIne("Echo: )0)",c);
}
Console.WriteLine("Done");
return 0;

Console.ReadLine Method()
This method reads the next line of characters from the standard input stream. It returns
the next line from the input stream, or a null reference if no more charcters are available. A
line is defined as a sequence of characters followed by a carriage return (hexadecimal
0x000d), a line feed (hexadecimal 0x000a). The returned string does not contain the
termination character(s). Consider the following code for illustration.
public class InsertTabs
{
private const int tabSize = 4;
private const string usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
public static int Main(String[] args)
{
StreamWriter writer = null;

if (args.Length < 2)
{
Console.WriteLine(usageTextt);
return 1;
}
try
{
write = new StramWriter(args[1]);
Console.SetOut(writer);
Console.SetIn(new StreamReader(args[0]));
}
catch(IOException e)
{
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
errorWriter.WriteLine(usageText);
return 1;
}
string line;
while((line = Console.ReadLine())!= null)
{
string newLine = line.Replace(("").PadRight(tabSize,'),"\t");
Console.WriteLine(newLine);
}
writer.Close();
//Recover the standard output stream so that a
// Completion message can be displayed.
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine("INSERTTABS has completed the processing of (0).", args[0]);
return 0;
}
}
Console.Write Method(Boolean)
This method writes the text representation of the specified Boolean value to the
standard output stream. The text representation of value is produced by
calling Boolean.Tostring. Consdier the following code for illustration.
public class FormatConverter
{
public static void Main(string[] args)
{
string lineInput;

while((lineInput = Console.ReadLine()) != null)


{
bool isFirstField = true;
foreach(string item in fields)
{
if (isFirstField)
isFirstField = false;
else
Console.Write(',');
try
{
Console.Write(Convert.ToByte(Convert.ToBoolean(item)));
}
catch(FormatException)
{
Console.Write(item);
}
}
Console.WriteLine();
}
}
}
Console.Write Method(String)
This method writes the specified string value to the standard output stream. If value is a
null reference, nothing is written to the standard output stream. Consider the following
code for illustration.
public class FormatConverter
{
public static void Main(string[] args)
{
string lineInput;

while((lineInput = Console.ReadLine()) != null)


{
bool isFirstField = true;
foreach(string item in fields)
{
if (isFirstField)
isFirstField = false;
else
Console.Write(',');
try
{
Console.Write(Convert.ToByte(Convert.ToBoolean(item)));
}
catch(FormatException)
{
Console.Write(item);
}
}
Console.WriteLine();
}
}
}

You might also like