You are on page 1of 9

C# Notes

What is C#?
C# pronounced as C Sharp) is a new computer-programming language developed by Microsoft
Corporation, S!" C# is a fully ob#ect-oriented programming language li$e #ava and is the first Compenent-
oriented language" %t has been designed to support the $ey feature of "&et 'ramewor$" %t is a simple, efficient
productive and type-safe language derived from the popular C and C(( language"
Why C#?
C and C(( have been the two most popular and most widely used languages in the software industry for
the past two decades" )hey provide programmers with a tremendous amount of power and control developing
scientific, commercial and business applications" *owever, these languages suffer from a number of shortcomings
in meeting the merging +orld +ide +eb re,uirements and standards" -f concern are the following.
)he high comple/ity of the language"
)heir long cycle-time
)hey are not truly ob#ect-oriented
)hey are not suitable for wor$ing with new web technologies"
)hey have poor type-safety
)hey are prone to costly programming errors
)hey do not support versioning
)hey are prone to memory lea$ages
)heir low productivity
)heir poor interoperability with the e/isting systems"
)hey are wea$ in consistency
)heir poor support for component programming"
0isual 1asic 201), a language promoted by Microsoft for overcoming these problems, also could not meet
some of the re,uirements of the www"
3ava, a language derived from C4C(( family, however, is truly ob#ect-oriented and has been widely used
for web applications for the past five years" nfortunately, 3ava has not retained some powerful C(( features
such as operator overloading" %t also lac$s inter-operability with code developed in other languages" !lthough
Microsoft attempted to transform 3ava and ma$e it a language of choice for their proposed new generation
"&5) platform"
Microsoft wanted an environment that is completely in tune with current and emerging +eb-programming
practices and one that easily integrates with e/isting systems" Microsoft therefore decided to design a new
language starting with a clean slate" )he result is C#, a simple and modern language that directly addresses
the needs of component-based software development"
Characteristics of C#
!s pointed out earlier, the main design goal of C# was simplicity rather than pure power" C# fulfills the
need for a language that is easy to write, read and maintain and also provides the power and fle/ibility of C(("
)he language that is designed for both computing and communications is characteri6ed by several $ey features"
C
C+
+
C# Jav
a
V
B
%ts is
Simple
Consistent
Modern
-b#ect-oriented
)ype-safe
0ersionable
Compatible
%nteroperable and
'le/ible
Simple
C# simplifies C(( by eliminating ir$some operators such as -7,.. and pointers" C# treats integer and
1oolean data types as two entirely different types" )his means that the use of 8 in place of 88in %f statement will
be caught by the compiler"
Consistent
C# supports a unified type system which eliminates the problem of varying ranges of integer types" !ll
types are treated as ob#ects and developers can e/tend the type system simply and easily"
Modern
C# is called a modern language due to a number of features it supports" %t supports
!utomatic garbage collection
9ich intrinsic model for error handling
:ecimal data type for financial applications"
Modern approach to debugging and
9obust security model
Object-Oriented
C# is truly ob#ect-oriented" %t supports all the three tenets of ob#ect-oriented systems, namely"
5ncapsulation
%nheritance and
;olymorphism
)he entire C# class model is built on top of the 0irtual -b#ect System 20-S) of the "&5) framewor$ %n C#,
everything is an ob#ect" )here are no more global functions, variables and constants"
Type-safe
)ype-safety promotes robust programs" C# incorporates a number of type-safe measures"
!ll :ynamically allocated ob#ects and arrays are initiali6ed to <ero"
se of any uninitiali6ed variables produces an error message by the compiler"
!ccess to arrays are range-chec$ed and warned if it goes out-of-bounds
C# does not permit unsafe casts
C# enforces overflow chec$ing in arithmetic operations"
9eference parameters that are passed are type-safe"
C# supports automatic garbage collection"
Versionable
Ma$ing new versions of software modules wor$ with the e/isting applications is $nown are versioning" C#
provides support for versioning with the help of new and oerride $eywords" +ith this support, a programmer
can guarantee that his new class library will maintain binary compatibility with the e/isting client applications"
Compatible
C# enforces the "&5) common language specifications and therefore allows inter-operation with other "&5)
languages"
C# provides support for transparent access to standard C-M and -=5 !utomation"
C# also permits interoperation with C-Style !;%s"
!le"ible
!lthough C# does not support pointers, we may declare certain classes and methods as unsafe and then
use pointers to manipulate them" *owever, these codes will not be type-safe"
#nter-operability
C# provides the support the using C-M ob#ects, no matter what language was used to another them" C#
also supports a special feature that enables a program to call out any native !;%"
$pplications of C#
!s pointed out earlier, C# is a new language developed e/clusively to suit the features of "&5) platform" %t
can be used for a variety of applications that are supported by the "&5) platform"
Console applications
+indows applications
:eveloping windows controls
:eveloping !S;"&5) pro#ects
Creating +eb Controls
;roviding +eb Services
:eveloping "&5) component library
)hey also added a number of additional features to ma$e C# a type-safe and web-enabled language"
The Ori%ins of &N'T Technolo%y
1efore going into the details of "&5) features further, we shall see how the concept of "&5) was evolved
over the past ten years" )he current technology of "&5) has gone through three significant phases of
development.
O(' technolo%y
COM technolo%y
&N'T technolo%y
)hese developments that too$ place during the >??@s are illustrated"
O(' Technolo%y
-=5 2-b#ect =in$ing and 5mbedding) technology was developed by Microsoft in the early >??@s to enable
easy interprocess communications" -=5 provided support to achieve the following.
)o embed documents from one application into another application
)o enable one application to manipulate ob#ects located in another application"
)his enabled users to develop applications which re,uired inter-operability between various products such as MS
+ord and MS 5/cel"
COM Technolo%y
)ill the advent of C-M technology, the monolithic approach had been used for developing software" 1ut
when programs become too large and comple/, the monolithic approach leads to a number of problems in terms
of maintainability and testing of software" )o overcome these problems, Microsoft introduced the component-based
model for developing software programs" %n the component-based approach, a program is bro$en into a number of
independent components where each one offers a particular service" 5ach component can be developed and tested
independently and then integrated it into the main system" )his technology is $nown as the Component -b#ect
Model 2C-M) and the software built using C-M is referred to as componentware"
C-M technology offers a number of benefits to developers and users" %t
9educes the overall comple/ity of software
5nables distributed development across multiple organi6ations or departments and
5nhance software maintainability"
&N'T Technolo%y
"&5) technology is third-generation component model" )his provides a new level of inter-operability
compared to C-M technology" C-M provides a standard binary mechanism for inter-model communication" )his
mechanism is replaced by an intermediate language called Microsoft %ntermediate =anguage 2MS%=) or simply %= in
the "&5) )echnology" 0arious "&5)-language compilers enforce inter-operability by compiling code into %=, which is
automatically compatible with other %= modules" !n inherent characteristic of %= code is metadata" Metadata is
data about data and describes its characteristics, including data types and locations" %= allows for true cross-
language integration" %n addition to %=, "&5) includes a host of other technologies and tools that will enable us
develop and implement +eb-based applications easily"
Common (an%)a%e *)ntime
)he Common =anguage 9untime, popularly $nown as C=9 is the heart and soul of the "&5) 'ramewor$" %t
also supports cross-language interoperability" )he C=9 provides a number of services that include"
=oading and e/ecution of programs
Memory isolation for applications
0erification of type safety
Compilation of %= into native e/ecutable code
;roviding metadata
Memory management 2automatic garbage collection)
5nforcement of security
%nteroperability with other systems
Managing e/ceptions and errors
Support for tas$s such as debugging and profiling
Common Type System +CTS,
)he "&5) framewor$ provides multiple language support using the feature $nown as Common )ype System
that is built into the C=9" )he C)S supports a variety of types and operations found in most programming
languages and therefore calling one language from another does not re,uire type conversions" !lthough C# is
specially designed for the "&5) ;latform, we can build "&5) programs in a number of other languages including C(
( and 0isual 1asic"
Common (an%)a%e Specification +C(S,
)he Common =anguage Specification defines a set of rules that enables interoperability on the "&5)
platform" )hese rules serve as a guide to third-party compiler designers and library builders" !pplication
;rogramming %nterfaces 2!;%s) that are designed following the rules of C=S can easily be used by all the "&5)
=anguages"
Microsoft #ntermediate (an%)a%e +MS#(,
MS%=, or simply %=, is an instruction set into which all the "&5) programs are compiled" %t is a$in to
assembly language and contains instructions for loading, storing, initiali6ing and calling methods" +hen we
compile a C# program or any program written in a C=S-compliant language, the source code is compiled into
MS%="
Mana%ed Code
!s we $now, the C=9 is responsible for managing the e/ecution of code compiled for the "&5) platform"
)he code that satisfies the C=9 at runtime in order to e/ecute is referred to as managed code" Compilers that are
compatible to the "&5) platform generate managed code" 'or e/ample, the C# compiler generates managed code"
)he managed code generated by C# 2and other compilers capable of generating managed code) is %= code" )he %=
code is then converted to native machine code by the 3%) compilers"
&N'T (an%)a%es
)he "&5) framewor$ is language neutral" Currently, we can use a number of languages for developing "&5)
applications" )hey include.
Natie to &N'T
C# 2Specially created for "&5))
C((
0isual 1asic
3script
Third-party lan%)a%es
C-1-=
5iffel
;erl
;ython
Small )al$
Mercury
Scheme
C# and the &N'T
C# is a new programming language introduced with "&5)" %t is a concise, elegant "&5) language"
)he C=9 e/tends a number of benefits to C# when it is implemented on the "&5) platform" )hese include.
%nteroperability with other languages
5nhanced security
0ersioning support
:ebugging support
!utomatic garbage collection
AM= support for web-based applications"
C# can be used to develop two categories of programs, namely,
5/ecutable application programs and
Component libraries
Compile Time 'rrors
&o matter how thoroughly the design is carried out, and no matter how much care is ta$en in coding, we
can never say that a program is totally error-free" ! program may contain two types of errors.
Synta/ 5rrors
=ogic 5rrors
+hile synta/ error will be caught by the compiler, logic errors should be eliminated by testing the program logic
carefully"
+hen the compiler cannot interpret what we are attempting to convey through our code the result is synta/ error"
C# program is a collection of to$ens, comments and white spaces" C# includes the following five types of
to$ens"
Beywords
%dentifiers
=iterals
-perators
;unctuators
-eywords.
!bstract, as, base, bool and etc",
/)nct)ators.
;arentheses2 )
1races C D
1rac$ets E F
SemicolonG
Colon.
Comma,
;eriod"
(iterals.
&umeric literals
1oolean literals
Character =iterals
&umeric =iterals
%nteger literals
)here are two types of integers, namely, decimal inte%ers and he"adecimal inte%ers"
:ecimal integers consist of a set of digits, @ through ? and embedded spaces, commas and
non-digit characters are not permitted between digits"
*e/adecimal integer it may also include alphabets ! through ' or a through f" @/H @/?f
9eal literals
! whole number, a decimal point, a fractional part, an e/ponent
1oolean =iterals
)here are two 1oolean literal values. Tr)e0 !alse
Character =iterals
Single Character literals I J, /
String literals I K*ello C#L, KH@@>L
1ata Types
0alue )ypes
;ointers
9eference )ypes
0alue )ypes
;redefined )ype
%ntegers, 9eal &umbers, 1ooleans, Characters
ser-defined )ypes
5numerations, Structures
9eference )ypes
;redefined types
-b#ects, Strings
ser-defined )ypes
Classes, !rrays, :elegates, %nterfaces
2o"in% and 3nbo"in%
%n ob#ect-oriented programming, methods are invo$ed using ob#ect" Since value types such as int and long
are not ob#ects, we cannot use them to call methods" 1o/ing means the conversion of a value type on the stac$ to
a object type on the heap" -b#ect type bac$ to a value type is $nown as unbo/ing"
2o"in%
0alue or reference can be assigned to an ob#ect without an e/plicit conversion"
%nt m8>@G
-b#ect om8mG
M8H@G
Console"+riteline 2m)G 44m8H@
Console"+riteline 2-m)G 44-m8>@
3nbo"in%
;rocess of converting the ob#ect type bac$ to the value type" %n contrast to bo/ing, unbo/ing is an e/plicit
operation using C-style casting"
%nt m8>@G
-b#ect om8mG 44bo/ m
%nt n82int)omG 44 unbo/ om bac$ to an int
C# supports a rich set of operators" C# operators can be classified into a number of related categories as
below.
!rithmetic -perators
9elational -perators
=ogical -perators
!ssignment -perators
%ncrement and decrement -perators
Conditional -perators
1itwise -perators
Special -perators
!rithmetic -perators
%nteger !rithmetic
9eal !rithmetic
Mi/ed-mode !rithmetic
(,-,M,4,N
9elation -perators . 40 45060650 550 7 5
=ogical -perators. 880 990 70 8090 :
!ssignment -perators
%ncrement and :ecrement -perators . ;; and <
Conditional -perator. ?.
Type Conersions
%mplicit Conversions
5/plicit Conversions
Methods in C#
%n ob#ect-oriented programming, ob#ects are used as building bloc$s in developing a program" )he code
designed to wor$ on the data is $nown as methods in C#" C# is a pure ob#ect-oriented language and therefore,
every method must be contained with a class remember, in other language li$e 01,C and C((, we can define
global functions that are not associated with a particular class"
1eclarin% Methods
Methods declaration has five parts.
&ame of the method 2methodname)
)ype of value the method return2type)
=ist of parameters 2formal-parameter-list)
1ody of the method
Method modifiers 2modifier)
Method modifiers
New. )he method hides an inherited method with the same signature"
/)blic. )he method can be accessed from anywhere, including outside the class"
/rotected. )he method can be accessed from within the class to which it belongs, or a type derived
from that class"
#nternal. )he method can be accessed from within the same program"
/riate. )he method can only be accessed from inside the class to which it belongs
Static. )he method does not operate on a specific instance of the class"
Virt)al. )he method can be overridden by a derived class"
$bstract. ! virtual method which defines the signature of the method, but doesnt provide an
implementation"
Oerride. )he method overrides an inherited virtual or abstract method
Sealed. )he method overrides an inherited virtual method, but cannot be overridden by any
classes which inherit from this class" Must be used in con#unction with override
'"tern. )he method is implemented e/ternally, in a different language"
The Main Method
!s mentioned earlier, C# programs start e/ecution at a method named Main2)" )his method must be the
static method of a class and must have either int or void as return type
;ublic static int Main2) or ;ublic static void Main2)
#no=in% Method
-nce methods have been defined, they must be activated for operations" )he process of activating method
is $nown as invo$ing or calling"
*ere, ob#ect name is the name of the ob#ect on which we are calling the method method name" the actual-
parameter-list is a comma separated list of !ctual values 2or e/pressions) that must match in type, order and
number with the formal parameter list of the methodname declared in the class" &ote that the invo$ing statement
is an e/ecutable one and therefore must end with a semicolon" )he values of the actual parameters are assigned
to the formal parameters at the time of invocation"
Nestin% of methods
)he class Nestin% defines two method namely =argest2) and Ma/2)" )he Method =argest2) calls the
method Ma/2) to determine the largest of the two numbers and then displays the result"
Method parameters
0alue ;arameters
9eference ;arameters
-utput ;arameters
;arameter arrays
Methods Oerloadin%
C# allows us to create more than one method with the same name, but with the different parameter line
and different definitions" )his is called method overloading" Method overloading is used when methods are
re,uired to perform similar tas$ but using different input parameters"
-verloaded methods must differ in number and4or type of parameters they ta$e" )his enables the compiler
to decide which one of the definitions to e/ecute depending on the type and number of arguments in the method
call" &ote that the methods return type does not play any role in the overload resolution"
sing the concept of method overloading, we an design a family of methods with one name but different
arguments lists" 'or e/ample, an overloaded add2) method handles different types of data as shown below"
2asic /rinciples of OO/
!ll ob#ect--riented languages employ three core principles, namely,
5ncapsulation
%nheritance and
;olymorphism
'ncaps)lation
5ncapsulation provides the ability to hide the internal details of an ob#ect from its users" )he outside user
may not be able to change the state of an ob#ect directly" *owever, the state of an ob#ect maybe altered indirectly
using what are $nown accessor and mutator methods" %n C#, encapsulation is implemented using the access
modifier $eywords public, private, and protected"
)he concept of encapsulation is also $now as data hiding or information hiding" +hen done properly, we
can create software blac$ bo/es that can be independently tested and used"
#nheritance
%nheritance is the concept we use to built new classes using the e/isting class definitions" )hrough
inheritance we can modify a class the way we want to create new ob#ects" )he original class is $nown as base or
parent class and the modified one is $nown as derived class or subclass or child class"
)he concept of inheritance facilitates the reusability of e/isting code and thus improves the integrity of
programs and productivity of programmers"
/olymorphism
;olymorphism is the third concept of --;" %t is the ability to ta$e more than one form" 'or e/ample, an
operation may e/hibit different behavior in different situations" )he behavior depends upon the types of data used
in the operation" 'or e/ample, an addition operation involving two numeric values will produce a sum and the
same addition operation will produce a string if the operands are string value instead of numbers" Similarly, a
method when called with one set of parameters may draw a circle but when called with another set of parameters
may draw a triangle"
;olymorphism is e/tensively used while implementing inheritance"
Constr)ctors
+e $now that all ob#ects that are created must be given initial values" +e have done this earlier using two
approaches" )he first approach uses the dot operator to access to instance variables and then assigns values to
them individually" %t can be a tedious approach to initiali6e all the variables of all the ob#ects"
)he second approach ta$es the help of a function li$e >et1ata to initiali6e each ob#ect individually using
statement li$e"
#nheritance and /olymorphism
%t is always nice if we could reuse something that already e/ists rather than creating the same over again"
C#, being a pure ob#ect-oriented language, supports this feature" %n fact, the ability to create new classes from
the e/isting classes is the ma#or motivation and power behind using --; languages"
C# classes can be reused in several ways" 9eusability is achieved by designing new classes, reusing all or
some of the properties of e/isting ones" )he mechanism of designing or constructing one class from another is
called inheritance" )his may be achieved in two different forms"
Classical form
Containment form
#nheritance Types
Single %nheritance2only one base class)
Multiple %nheritance 2several base classes)
*ierarchical %nheritance 2one base class, many subclasses)
Multilevel %nheritance :erived from a derived class)
Class members Visibility
;ublic
;rotected
;rivate
%nternal
;rotected internal
/ro%rams
Co)ntin% with if Statement
sing systemG
Class %f)est
C
;ublic static void main2)
C
%nt %, count, count>, countHG
'loat EF weight8 COJ"@', JJ"@', OP"@'D
'loat EF height8 C>PQ"J', >PO"H', >QR"@'D

You might also like