Predefined C# Value Types: Boolean Types Are Declared Using The Keyword, Bool. They Have Two Values: True or False
Predefined C# Value Types: Boolean Types Are Declared Using The Keyword, Bool. They Have Two Values: True or False
sbyte: Holds 8-bit signed integers. The s in sbyte stands for signed, meaning that the variable's value can be either positive or negative. The smallest possible value for ansbyte variable is -128 the largest possible value is 12!. byte: Holds 8-bit unsigned integers. "nli#e sbyte variables, byte variables are not signed and can only hold positive numbers. The smallest possible value for a byte variable is $ the largest possible value is 2%%. short: Holds 1&-bit signed integers. The smallest possible value for a short variable is -'2,!&8 the largest possible value is '2,!&!. ushort: Holds 1&-bit unsigned integers. The u in ushort stands for unsigned. The smallest possible value of an ushort variable is $ the largest possible value is &%,%'%. int: Holds '2-bit signed integers. The smallest possible value of an int variable is -2,1(!,(8',&(8 the largest possible value is 2,1(!,(8',&(!. uint: Holds '2-bit unsigned integers. The u in uint stands for unsigned. The smallest possible value of a uint variable is $ the largest possible value is (,2)(,)&!,2)%. long: Holds &(-bit signed integers. The smallest possible value of a long variable is ),22','!2,$'&,8%(,!!%,8$8 the largest possible value is ),22','!2,$'&,8%(,!!%,8$!. ulong: Holds &(-bit unsigned integers. The u in ulong stands for unsigned. The smallest possible value of a ulong variable is $ the largest possible value is 18,((&,!((,$!',!$),%%1,&1%. char: Holds 1&-bit "nicode characters. The smallest possible value of a char variable is the "nicode character *hose value is $ the largest possible value is the "nicode character *hose value is &%,%'%. float: Holds a '2-bit signed floating-point value. The smallest possible value of a float type is appro+imately 1.% times 1$ to the (%th po*er the largest possible value is appro+imately '.( times 1$ to the '8th po*er. double: Holds a &(-bit signed floating-point value. The smallest possible value of a double is appro+imately % times 1$ to the '2(th the largest possible value is appro+imately 1.! times 1$ to the '$8th. decimal: Holds a 128-bit signed floating-point value. ,ariables of type decimal are good for financial calculations. The smallest possible value of a decimal type is appro+imately 1 times 1$ to the 28th po*er the largest possible value is appro+imately !.) times 1$ to the 28th po*er. bool: Holds one of t*o possible values, true or false. The use of the bool type is one of the areas in *hich -. brea#s from its - and -// heritage. 0n - and -//, the integer value $ *as synonymous *ith false, and any non1ero value *as synonymous *ith true. 0n -., ho*ever, the types are not synonymous. 2ou cannot convert an integer variable into an e3uivalent bool value. 0f you *ant to *or# *ith a variable that needs to represent a true or false condition, use a bool variable and not an int variable.
Integral Types
In C#, an integral is a category of types. For anyone confused because the word Integral sounds like a athe atical ter , fro the perspective of C# progra ing, these are actually defined as Integral types in the C# progra ing language specification. They are whole nu bers, either signed or unsigned, and the char type. The char type is a !nicode character, as defined by the !nicode "tandard. For ore infor ation, visit The !nicode #o e $age.
Integral types are well suited for those operations involving whole nu ber calculations. The char type is the e0ception, representing a single !nicode character. 1s you can see fro the table above, you have a wide range of options to choose fro , depending on your re2uire ents.
Floating point types are used when you need to perfor operations re2uiring fractional representations. #owever, for financial calculations, the decimal type is the best choice because you can avoid rounding errors.
1nother useful feature of C# strings is the "erbatim literal, which is a string with a @ sy bol prefi0, as in @"Some string". ?erbati literals ake escape se2uences translate as nor al characters to enhance readability. To appreciate the value of verbati literals, consider a path state ent such as "c:\\topdir\\subdir\\subdir\\myapp.exe" . 1s you can see, the backslashes are escaped,
causing the string to be less readable. 6ou can i prove the string with a verbati like this: @"c:\topdir\subdir\subdir\myapp.exe".
literal,
That is fine, but now you have the proble where 2uoting te0t is not as easy. In that case, you would specify double double 2uotes. For e0a ple, the string "copy \"c:\\source file name with spaces.txt\" c:\\newfilename.txt" would be written as the verbati literal @"copy ""c:\source file name with spaces.txt"" c:\newfilename.txt" .
#$ %perators
=esults are co puted by building e0pressions. These e0pressions are built by co bining variables and operators together into state ents. The following table describes the allowable operators, their precedence, and associativity.
Operators
#ategory (by precedence) $ri ary !nary Iultiplicative 1dditive "hift =elational 32uality 9ogical 1<5 9ogical PQ= 9ogical Q= Conditional 1<5 Conditional Q= <ull Coalescing Ternary 1ssign ent
9eft associativity eans that operations are evaluated fro left to right. =ight associativity ean all operations occur fro right to left, such as assign ent operators where everything to the right is evaluated before the result is placed into the variable on the left.
using System; class MainClass { static int? GetNullableInt() { return null; } static string GetStringValue() { return null; } static void Main() { ?? o!erator e"am!le# int? " $ null; y $ "% unless " is null% in &'ic' case y $ ()# int y $ " ?? (); *ssign i to return value o+ met'od% unless return value is null% in &'ic' case assign de+ault value o+ int to i# int i $ GetNullableInt() ?? de+ault(int); string s $ GetStringValue(); ?? also &or,s &it' re+erence ty!es# -is!lay contents o+ s% unless s is null% in &'ic' case dis!lay ./ns!eci+ied.# Console#0rite1ine(s ?? ./ns!eci+ied.); } }
Selection statements
int i=3; if (condition) { //CODE } elseif (condition) { //CODE
} else { //CODE } switch (expression) { c"se #$ // CODE bre"%; c"se &$ //CODE bre"%; def" lt$ //CODE bre"%; } Example int i=3; switch (i) { c"se #$ 'ess"!e(ox)*how(+i=#+); bre"%; c"se &$ 'ess"!e(ox)*how(+i=&+); bre"%; def" lt$ 'ess"!e(ox)*how(+i=,+); bre"%; } // sbyte, byte, short, short, int, int, lon!, lon!, ch"r, strin!
Iteration statements
while ( condition ) { //CODE } do{ //CODE }
while ( condition ); for (initi"li-"tion; condition; iter"tion){ //CODE } fore"ch (int te.pEle.ent in /rr"y0Collection){ //CODE }
Creating Arrays in C#
/ C1 "rr"y ."y be cre"ted in " n .ber of different w"ys) One w"y is to si.ply decl"re "n "rr"y witho t initi"li-in! it with "ny 2"l es) 3he synt"x for this is "s follows$
ty!e23 arrayname;
4n the "bo2e ex".ple, type represents the type of d"t" to be stored in the "rr"y (or ex".ple, strin!, int, deci."l etc)) 3he s5 "re br"c%ets (67) indic"te th"t this is the decl"r"tion for "n "rr"y "nd arrayname is the n".e by which the "rr"y is to referred) 8otice th"t this is 9 st " decl"r"tion "nd in C1, the si-e of the "rr"y is re5 ired) 3herefore, "n "rr"y wo ld h"2e to be inst"nti"ted "nd bec" se "rr"ys in C1 is inherited fro. the *yste.)/rr"y cl"ss :or ex".ple, we c"n decl"re "n "rr"y of strin!s c"lled .yColors "s follows$
string23 myColors;
4n this ex".ple, we h"2e decl"red the "rr"y b t not "ssi!ned "ny 2"l es to it) 3o "ssi!n 2"l es "fter "n "rr"y h"s been decl"red the new st"te.ent . st be sed co.bined with " co.." sep"r"ted list of 2"l es$
string23 myColors; myColors $ ne& string23 {.red.% .green.% .yello&.% .orange.% .blue.};
/n "rr"y ."y "lso be initi"li-ed in the decl"r"tion line si.ply by pl"cin! the co.." sep"r"ted list of 2"l es "fter the decl"r"tion$
string23 myColors $ {.red.% .green.% .yello&.% .orange.% .blue.};
/nother option is to decl"re the si-e of the "rr"y when it is cre"ted) :or ex".ple, to decl"re "n "rr"y of si-e #; si.ply pl"ce the si-e 2"l e within the s5 "re br"c%ets of the new st"te.ent$
myColors $ ne& string243;
3his will reser2e the sp"ce re5 ired for the f ll "rr"y witho t "ct "lly pl"cin! "ny 2"l es into the "rr"y) :in"lly, this "ppro"ch ."y "lso be co.bined with the co.." sep"r"ted 2"l e list ("ltho !h the n .ber of 2"l es . st ."tch the si-e specified)$
string243 myColors $ {.red.% .green.% .yello&.% .orange.% .blue.};
3his cre"tes " . ltidi.ension"l "rr"y cont"inin! three rows "nd three col .ns) / row exists for e"ch boo%, "nd e"ch boo% cont"ins three col .ns consistin! of title, " thor "nd 4D)
:or ex".ple$
string23 myColors $ {.red.% .green.% .yello&.% .orange.% .blue.}; System#Console#0rite1ine(myColors2)3);
<hen exec ted, the "bo2e code will o tp t the word +!reen+ since this is the strin! cont"ined "t index # position in the "rr"y) *i.il"rly, the 2"l e "t " p"rtic l"r index point in the "rr"y ."y be ch"n!ed sin! the "ccessor not"tion co.bined with the "ssi!n.ent oper"tor (=)) :or ex".ple, to ch"n!e the 2"l e of the first ite. in the "rr"y$
myColors2<3 $ .indigo.;
="l es in " . ltidi.ension"l "rr"y ."y be "ccessed by specifyin! the index 2"l es for e"ch di.ension sep"r"ted by co.."s) :or ex".ple, to "ccess the " thor (index position # of the second di.ension) of the boo% loc"ted "t index position & of the first di.ension in o r . ltidi.ension"l "rr"y$
System#Console#0rite1ine(boo,s25%)3);
3he "bo2e line of code will o tp t the n".e +'i%e >"store+ (i)e the " thor the 3rd boo% in the "rr"y))
4n the c"se of " . ltidi.ension"l "rr"y, the Length property will cont"in the entire len!th of the "rr"y (incl din! "ll di.ensions)) :or ex".ple, o r books two?di.ension"l "rr"y will h"2e " len!th of @)
3he "bo2e ex".ple will sort the ele.ents of the .yColors "rr"y into "lph"betic"l order$
blue green orange red yello&
3he order of the ele.ents ."y s bse5 ently be re2ersed sin! the System.Array.Reverse() .ethod$
System#*rray#>everse (myColors); +or (int i$<; i=myColors#1engt'; i::) { System#Console#0rite1ine(myColors2i3); }
3he 2"l es in "n "rr"y ."y be cle"red sin! the System.Array.Clear() .ethod) 3his .ethod cle"rs e"ch ite. in "n "rr"y to the def" lt 2"l e for the type (f"lse for boole"n, ; for n .eric "nd n ll for " strin!))
3he scope of "ccessibility is li.ited within the cl"ss or str ct "nd the cl"ss deri2ed (4nherited) fro. this cl"ss) internal # 3he intern"l "ccess .odifiers c"n "ccess within the pro!r". th"t cont"in its decl"r"tions "nd "lso "ccess within the s".e "sse.bly le2el b t not fro. "nother "sse.bly) protected internal # >rotected intern"l is the s".e "ccess le2els of both protected "nd intern"l) 4t c"n "ccess "nywhere in the s".e "sse.bly "nd in the s".e cl"ss "lso the cl"sses inherited fro. the s".e cl"ss)
1 C# Class Considered being the pri ary building block of the language. 4hat I ean by the pri ary building block of the language is that every ti e you work with C# you will create Classes to for a progra . 4e use Classes as a te plate to put the properties and functionalities or behaviors in one building block for so e group of obUects and after that we use that te plate to create the obUects we need. For e0a ple, 4e need to have persons obUects in our progra so the first thing to do here is to create a Class called $erson that contains all the functionalities or behaviors and properties of any person and after that we will use that Class or te plate to create as any obUects as we need. Creating obUect of a specific class type called 7instance of the class7. 5on8t worry if you didn8t grasp it '**L and don8t worry if you don8t know what8s the Class and QbUect8s properties and functionalities or behaviors because we still in the beginning and until now I didn8t give any code e0a ples. "o let8s take a brief of what8s the Class and what8s an obUect T The #lass , Is a building block that contains the properties and functionalities that describe so e group of obUects, 4e can create a class $erson that contains: '& The properties of any nor al person on the earth like : #air Color, 1ge, #eight, 4eight, 3yes Color. (& The functionalities or behaviors of any nor al person on the earth like : 5rink water, 3at, Vo to the work and later we will see how we can i ple ent the functionalities or behaviors and properties. There are ( kinds of classes : The built&it classes that co e with the .<3T Fra ework and called Fra ework Class 9ibrary. 1nd the progra er defined&classes which we create it. The class contains data Ain the for of variables and propertiesB and behaviors Ain the for process these dataB. 4e will understand this concept ore later in the article. of ethods to
4hen we declare a variable in a class we call it e ber variables or instance variables. The na e instance co e fro the fact that when we create an obUect we instance a class to create that obUect so instance of a class eans obUect of that class and instance variable eans variable that e0ists in that class. The %b)ect , It8s obUect of so e classification Aor class, or type. 1ll eans the sa e thingB and when you create the obUect you can specify the properties of that obUect. 4hat I ean here is e as an obUect can have a different properties A#air Color, 1ge, #eight, 4eightB of you as another obUect. For e0a ple, I have a brown eyes and you have a green eyes so when I create ( obUects I will specify a brown color for y obUect8s 3yes Color property and I will specify a green color for your obUect8s 3yes Color property. "o to co plete y introduction to Classes we ust discuss $roperties and ?ariables.
Properties and -ariables, ?ariables declared in a class store the data for each instance, 4hat that eans T eans that when you instantiate this class Athat is, 4hen you create an obUect of this classB the obUect will allocate a e ory locations to store the data of its variables. 9et8s take an e0a ple to understand it well. class ;erson { !ublic int *ge; !ublic string ?airColor; } This is our si ple class which contains ( variables. 5on8t worry about !ublic keyword now because we will talk about it later . <ow we will instantiate this class Athat is, 4hen you create an obUect of this classB.
static void Main(string23 args) { ;erson Mic'ael $ ne& ;erson(); ;erson Mary $ ne& ;erson(); S!eci+y some values +or t'e instance variables Mic'ael#*ge $ 5<; Mic'ael#?airColor $ .8ro&n.; Mary#*ge $ 54; Mary#?airColor $ .8lac,.; !rint t'e console@s screen some o+ t'e variable@s values Console#0rite1ine(.Mic'ael@s age $ {<}% and Mary@s age $ {)}.%Mic'ael#*ge% Mary#*ge); Console#>ead1ine();
"o we begin our Iain ethod by creating ( obUects of $erson type. 1fter creating the ( obUects we initiali>e the instance variables for obUect Iichael and then for obUect Iary. Finally we print so e values to the console. here when you create Iichael obUect C# co piler allocate a e ory location for the ( instance variables to put the values there. 1lso the sa e thing with Iary obUect the co piler will create ( variables in the e ory for Iary obUect. "o each obUect now contains a different data. <ote that we directly accessed the variables and we put any values we want, =ight T so aybe so eone doesn8t like e will put in y obUect8s variable 1ge value of '(* years so I will not get any kind of Uobs. But wait there are a solution for this proble . 4e will use properties. Properties, $roperties is a way to access the variables of the class in a secure using properties. class ;erson { !rivate int age; !rivate string 'airColor; !ublic int *ge { get { return age; } set { i+(value =$ A4 BB value C$ )D) { age $ value; } else age $ )D; } } !ublic string ?airColor { get { return 'airColor; } set anner. 9et8s see the sa e e0a ple
{ } } }
'airColor $ value;
I ade so e odifications but please Uust care about the new ( properties that I created it here. "o the property consists of ( accessor. The get accessor which is responsible of retrieving the variable value, 1nd the set accessor which is responsible of odifying the variable8s value. "o The get accessor code is very si ple we Uust use the keyword return with the variable na e to return its value. so the following code: get
{ } return 'airColor;
return the value stored in hairColor. <ote :the keyword value is a reserved keyword by C# Athat is, reserved keywords eans that these keywords own only by C# and you can8t create it for other purpose. For e0a ple, 6ou can8t create a variable called value .If you did that C# co piler will generate an error and to ake things easier ?isual "tudio.<3T will color the reserved keywords to blue.B 9et8s put this code at work and after that discuss the set accessor. static void Main(string23 args) { ;erson Mic'ael $ ne& ;erson(); ;erson Mary $ ne& ;erson(); S!eci+y some values +or t'e instance variables Mic'ael#*ge $ 5<; Mic'ael#?airColor $ .8ro&n.; Mary#*ge $ 54; Mary#?airColor $ .8lac,.; !rint t'e console@s screen some o+ t'e variable@s values Console#0rite1ine(.Mic'ael@s age $ {<}% and Mary@s age $ {)}.%Mic'ael#*ge% Mary#*ge); Console#>ead1ine();
#ere I created the sa e obUects fro last e0a ple the odifications that I used only properties to access the variable instead of access it directly. 9ook at the following line of code Mic'ael#*ge $ 5<; 4hen you assign a value to the property like that C# will use the set accessor. The great thing with the set accessor is that we can control the assigned value and test it and aybe change to in so e cases. 4hen you assign a value to a property C# change the value in a variable and you can access the variable8s value using the reserved keyword value e0actly as I did in the e0a ple. 9et8s see it again here.
set
#ere in the code I used i+ state ent to test the assigned value because for so e reason I want any obUect of type $erson to be in age between '% and ,+. #ere I test the value and if it in the range then si ply I will store it in the variable age and it it8s not in the range I will put '% as a value to age. It was Uust a si ple e0a ple for the properties but there is a co plete article about properties soon. .o+ +e create ob)ects and classes / 4e create classes by define it like that: using the keyword class followed by the class na e like that class ;erson then we open a left brace 7W7 and after we write our ethods and properties we close it by a right brace 7X7. That8s how we create a class. 9et8s see how we create an instance of that class. In the sa e way as we declare a variable of type int we create an obUect variable of $erson type with so e odifications: int age; ;erson Mic'ael $ ne& ;erson(); In the first line of code we specified integer variable called age. In the second line we specified first the type of QbUect we need to create followed by the obUect8s na e followed by a reserved operator called ne& and we end by typing the class na e again followed by parenthesis 7AB7. 9et8s understand it step&by&step. "pecifying the class na e at the beginning tell the C# Co piler to allocate a e ory location for that type AC# co piler knows all the variables and properties and ethods of the class so it will allocate the right a ount of e oryB. Then we followed the class na e by out obUect variable na e that we want it. The rest of the code 7$ ne& ;erson();. call the obUect8s constructor. 4e will talk about constructor later but for now understand that the constructor is a way to initiali>e your obUect8s variable while you are creating it not after you create it. For e0a ple, The Iichael obUect we created it in the last section can be written as following : ;erson Mic'ael $ ne& ;erson(5<% .8ro&n.); here I specified the variable8s values in the para eter list so I initiali>ed the variables while I8 creating the obUect. But for this code to work we will need to specify the constructor in the $erson class and I will not do that here because constructor section will co e in later articles. I think you got a good introduction about Classes and QbUects not I will co plete in in y ne0t article and I will talk about constructors and building block scoping. I hope you got a new thing fro y article.
Understanding Constructors in C#
Constr ctors "re sed for initi"li-in! the .e.bers of " cl"ss whene2er "n ob9ect is cre"ted with the def" lt 2"l es for initi"li-"tion) 4f " cl"ss is not defined with the constr ctor then the CBA (Co..on 7anguage A nti.e) will pro2ide "n i.plicit constr ctor which is c"lled "s Def" lt Constr ctor) / cl"ss c"n h"2e "ny n .ber of constr ctors pro2ided they 2"ry with the n .ber of "r! .ents th"t "re p"ssed, which is they sho ld h"2e different si!n"t res)
Constr ctors do not ret rn " 2"l e) Constr ctors c"n be o2erlo"ded) 4f " cl"ss is defined with static "nd Non-static constr ctors then the pri2ile!e will be !i2en to the 8on? st"tic constr ctors)
3he followin! "re the "ccess .odifiers for constr ctors, &u"lic # / constr ctor th"t is defined "s public will be c"lled whene2er " cl"ss is inst"nti"ted) &rotected # / constr ctor is defined "s protecte in s ch c"ses where the b"se cl"ss will initi"li-e on its own whene2er deri2ed types of it "re cre"ted) &ri$ate # / constr ctor is defined "s private in s ch c"ses whene2er " cl"ss which cont"ins only st"tic .e.bers h"s to be "ccessed will "2oid the cre"tion of the ob9ect for the cl"ss) Internal # /n intern"l constr ctor c"n be sed to li.it concrete i.ple.ent"tions of the "bstr"ct cl"ss to the "sse.bly definin! the cl"ss) / cl"ss cont"inin! "n intern"l constr ctor c"nnot be inst"nti"ted o tside of the "sse.bly) External # <hen " constr ctor is decl"red sin! "n e!tern .odifier, the constr ctor is s"id to be "n extern"l constr ctor)
'ypes of Constructors
i! Static # Csed for initi"li-in! only the st"tic .e.bers of the cl"ss) 3hese will be in2o%ed for the 2ery first ti.e the cl"ss is bein! lo"ded on the .e.ory) 3hey c"nnot "ccept "ny "r! .ents) *t"tic Constr ctors c"nnot h"2e "ny "ccess .odifiers) *ynt"x ???? *t"tic Cl"ss8".e() { //4niti"li-"tion st"te.ents;
} ii! (on)Static # "re sed for initi"li-in! the 8on?*t"tic "nd *t"tic .e.bers of " cl"ss) 3hese will be in2o%ed e2eryti.e " new ob9ect is defined for " cl"ss) *ynt"x ??? > blic Cl"ss8".e(6"r!s4nfo7) { //4niti"li-"tion st"te.ents; } Example # Csin! *yste.; Cl"ss *".pleConstr ctor { p blic st"tic int s; p blic int ns; st"tic *".pleConstr ctor() { s = #;; //ns = &;; ??? Error c"nnot be "ssi!ned li%e this } p blic *".pleConstr ctor() { ns=#;;; s=&;;; } } Cl"ss Cse*".pleConstr ctor {
p blic st"tic 2oid '"in() { *".pleConstr ctor sc = new *".pleConstr ctor(); Console)<riteBine(DEF{;},{#}DEG,sc)s, *".pleConstr ctor)s, sc)ns); }l }l Error(C"nnot c"ll li%e this) 4f yo obser2e in the "bo2e ex".ple the st"tic 2"ri"ble HnsI c"nnot be "ssi!ned " 2"l e in the st"tic Constr ctor "s it is " 8on?st"tic .e.ber of the cl"ss "nd " st"tic constr ctor c"nnot initi"li-e " 8on?*t"tic .e.ber) /lso "s yo see in the "bo2e code the 8on?st"tic constr ctor initi"li-in! the 2"l es for both the st"tic "nd 8on? *t"tic .e.bers of cl"ss, when we s"y HscI we "re cre"tin! "n ob9ect for the cl"ss "nd sin! the ob9ect we do the c"ll the .ethods, it is not 2"lid to c"ll " st"tic .e.ber of cl"ss sin! the ob9ect of the cl"ss we h"2e to c"ll it thro !h the .ethod n".e/Constr ctor n".e thro !h the .e.ber will be in2o%ed)
Introduction
8efore designing a class, *e should have a very clear understanding about constructor. 0n this article 0 *ill discuss definition, types and features of constructor. efinition 9 constructor loo#s li#e a special method having no return type and its name is same *ith the class name. 0f *e do not declare constructor e+plicitly for a class, compiler *ill create a default constructor at run time. !ccess "odifiers 9ccess modifiers of constructor can be public, private, protected, internal and e+tern. 9 public constructor is called *hen the class is instantiated. 9 private constructor prevents the creation of the ob6ect of the class. 0t is used in classes having only static members. 9 class having internal constructor cannot be instantiated outside of the assembly. 9 protected constructor of base class can only be called from the derived class *ithin derived class constructor. :hen a constructor having an e+tern modifier, the constructor is said to be an e+ternal constructor, because the same does not provide any actual implementation. 4emember that a private constructor can be accessed by a public constructor of the same class through constructor chaining.
#ypes of Constructor
-onstructor is of t*o types: 5tatic -onstructor and 0nstance -onstructor Static Constructor 5tatic constructors are called before the first instance of the class is created or any static members are accessed or used *hichever is earlier. ;ollo*ings are the features of static constructor: 9 5tatic constructor cannot be overloaded. There is no access modifier in 5tatic constructor and they don't ta#e any arguments also. The static constructor for a class e+ecutes only once throughout the life time of the program.
class ;arent { !ublic ;arent() { Console#0rite1ine(.Instance Constructor called.); } static ;arent() { Console#0rite1ine(.Static Constructor called.); } } class ;rogram { static void Main(stringBEF);3 args) { ;arent ! $ ne& ;arent(); ;arent !) $ ne& ;arent(); ;arent !5 $ ne& ;arent(); } } 5tatic constructor does not support -onstructor -hanning. 5tatic constructor can call only static members. 5tatic constructor is getting called before instance constructor.
class ;arent { !ublic ;arent() { Console#0rite1ine(.;arent -e+ault Constructor.); } !ublic ;arent(int ") { Console#0rite1ine(.;arent Constructor 0it' Single ;arameter.); } static ;arent() { Console#0rite1ine(.Static Constructor.); } } class C'ild G ;arent { !ublic C'ild()Gbase()<) { Console#0rite1ine(.C'ild Constructor.); } } class ;rogram { static void Main(string23 args) { C'ild c'ild $ ne& C'ild();
} } Instance Constructor 0nstance constructor is used to create and initiali1e instance and it is invo#ed *hen *e create a ne* ob6ect of the class.
$eatures of Constructor
-onstructor having different features as follo*s: -onstructor can not be virtual. :hen constructor is invo#ed the virtual table *ould not be available in the memory Constructor Chaining -onstructor chaining means call one constructor from another constructor. 0n order to call one constructor from another, *e use base <parameters= or: this <parameters= :e use base <parameters= to call a constructor in the base class and *e use this <parameters= to call a constructor in the current class. Inheritance 9 constructor of a base class can not be inherited to its derived class. 8ut base class constructor or parent class constructor can be invo#ed from derived class or child class. class ;arent { !ublic ;arent() { Console#0rite1ine(.;arent -e+ault Constructor.); } !ublic ;arent(int ") { Console#0rite1ine(.;arent Constructor 0it' Single ;arameter.); } } class C'ild G ;arent { !ublic C'ild()Gbase()<) { Console#0rite1ine(.C'ild Constructor.); } } class ;rogram { static void Main(string23 args) { C'ild c'ild $ ne& C'ild(); } }
Overloading -onstructor can be overloaded. 0n the follo*ing code snippet, there are four overloaded constructor:
!ublic Sam!le()//Default constructor without parameter. { } !ublic Sam!le(int iVal) //Constructor with one parameter. { } !ublic Sam!le(int iVal% string strVal) //Constructor with two !arameters# { } !ublic Sam!le(string strVal%int iVal)//Constructor with two !arameters in di++erent order# { }
estructor
>estructors are used to destruct instances of classes. ;ollo*ing are features of destructor: 9 class can have one destructor only. >estructors cannot be inherited or overloaded. >estructors are invo#ed automatically. >estructor can not have modifiers or parameters. :hen destructor is called, ;inali1e is called from destructor implicitly. :hen derived class destructor is called, the base class destructor is also getting called. class ;arent { H ;arent() // destructor { //Code for cleanup resources } }
%&ecution Order
8ase constructor is getting called first. 0n general, destructors are called in the reverse order of the constructor calls. ;or e+ample, if class 9 is the base class and class 8 inherit class 9 and class - inherit class 8. -onstructor *ill be fired for class 9 first, class 8 second and at last for class -. 8ut destructor *ill be fired in reverse order: class - first, class 8 second and at last for class 9.
9 copy constructor is a special constructor used to create a ne* ob6ect as a copy of an e+isting ob6ect. This constructor ta#es a single argument: a reference to the ob6ect to be copied. "nli#e some languages, -. does not provide a copy constructor. 0t is a great convenience to create copy constructor for -. classes using 4eflection. The advantage of 4eflection is that *e don't re3uire any modification on the -opy -onstructor code as long as *e define a ?roperty for ne*ly added fields. 5imilarly, no code modification is re3uired if *e drop a field. Here is a class called ?erson defined in a namespace called -lass7ibrary *hich simulates a -opy -onstructor using reflection: namespace ClassLibrary { public enum GenderType { FEMALE, MALE } public class Person { string name; GenderType gender; int age; //default constructor public Person() { } //copy constructor using Reflection public Person(Person person) { Type theType = Type.GetType("ClassLibrary.Person"); System.Reflection.PropertyInfo[] properties = theType.GetProperties(); foreach (System.Reflection.PropertyInfo property in properties) { System.Reflection.MethodInfo getMethod = property.GetGetMethod(); System.Reflection.MethodInfo setMethod = property.GetSetMethod(); object val = getMethod.Invoke(person, null); object[] param = new object[] { val }; setMethod.Invoke(this, param); } } public string Name { get { return name; } set { name = (string)value; } } public GenderType Gender { get { return gender; } set { gender = (GenderType)value; } } public int Age { get { return age; } set { age = (int)value; } } } }
9nd here is some small test code: Person me = new Person(); me.Name = "pdas"; me.Gender = GenderType.MALE; me.Age = 30; Person copyOfMe = new Person(me);
4n the E.ployee cl"ssIs def" lt constr ctor 4 sed the +this+ %eyword to initi"li-e the p blic fields :irst8".e "nd B"st8".e, so this %eyword pretends th"t yo "lre"dy h"2e "n inst"nce of the E.ployee cl"ss)
:or e)!) *t"tic =oid '"in() 4t is c"lled by the oper"tin! syste. on pro!r". exec tion 3o "ccess the st"tic .e.ber weMll se Cl"ss8".e)st"tic.e.ber <hen " 2"ri"ble is decl"red "s st"tic intern"lly wh"t h"ppens is th"t "ll the inst"nces of the cl"ss sh"re the s".e st"tic 2"ri"ble) / st"tic 2"ri"ble is initi"li-ed when its cl"ss is lo"ded) 4f not initi"li-ed explicitly then it is initi"li-ed to -ero for n .eric 2"ri"ble n ll in c"se of ob9ect references f"lse for boole"n StaticMethod? they c"n only cont"in st"tic .e.ber "nd c"ll other st"tic .ethod) 4f we need to "ccess the. th"n it c"n be done thro !h the ob9ect of th"t cl"ss cl"ss N".e { 2oid strin! !etN".e8".e() { OOOOOO) } p blic st"tic 2oid !et8".e3hro !h*t"tic(N".e !) { !)!etN".e8".e(); // "ccessin! st"tic .ethod } } <hen to se the., <ell we c"n se the. when we need to ."int"in infor."tion "pplic"ble to the entire cl"ss) * ppose we h"2e " cl"ss E.ployees there we c"n h"2e " st"tic co nt 2"ri"ble to %eep tr"c% of no of e.ployees) cl"ss E.ployees { st"tic in co nt=;; p blic E.ployees() { co ntPP; } QE.ployees { co ntR; } }
<h"t "re st"tic Constr ctors, 3hey c"n be sed to initi"li-e the st"tic 2"ri"bles) 3hey "re c"lled " to."tic"lly "nd before the inst"nce constr ctor (if c"lled "ny)) for "bo2e cl"ss st"tic E.ployees() // no other "ccess .odifiers for the. {} <h"t "re st"tic cl"sses, / cl"ss whose ob9ects c"nMt be cre"ted "nd which c"n only h"2e st"tic .e.bers) 3hey c"nMt be inherited "s well) 3hey c"n h"2e st"tic constr ctor <hy se st"tic cl"sses, 4t c"n be sed to !ro p rel"ted st"tic .ethod)