An Introduction To C#
An Introduction To C#
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.
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.
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
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
When you execute this C# program you have to pass two arguments with the filename.
you will get the output like Arguments-1 test1 Argument-2 test2
Introduction to C# Programming
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
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
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 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
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
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.
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
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:
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 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
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.
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);
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("Main Menu");
Console.WriteLine("1. Red");
Console.WriteLine("2. Green");
Console.WriteLine("3. Yellow");
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
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
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.
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.
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.
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();
class ComparisonOpeOverloading
{
public static void Main()
{
Over ob = new Over();
ob.Show();
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");
}
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.
throw exception_obj;
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.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();
}
c = a + b;
Console.WriteLine("Sum = "+c);
}
c = a - b;
Console.WriteLine("Subtraction = "+c);
}
c = a * b;
Console.WriteLine("Multiplication = "+c);
}
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.
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;