Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
33 views
76 pages
Chap 10 11
Uploaded by
mr.arjunb27
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save chap 10 11 For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
33 views
76 pages
Chap 10 11
Uploaded by
mr.arjunb27
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save chap 10 11 For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save chap 10 11 For Later
You are on page 1
/ 76
Search
Fullscreen
10 10 Introducing C# 2010 ee eee eee ae Need of C# 360 C# pre-processor Directives ¥ 360 New Features of C#2010 361 Creating @ Simple CH 2010 Gonsols Appleton Identifiers and Keywords Data Types, Variabies, and Constant __Expressions and Operatorscw 4 commonly known as C#, is one of the intermediate Programming languages used to It is an object-oriented programming language, which combine: the power an, wy and objectonented approach of Java, and ereativeness of Visual Basie Sines Wo jiieney use multiple inhentance and pointers but provide garbage collection at runti fava, me. Moreover, connect inciades the useful operations, such as operator overloading, enimerations) preipmaegeee Java, cy and function pointers, It also supports the concept of propertie directives, Pointer, C# 2010 has teen greatly improved, as it now includes new c mpiler features, improved debug b ng techniques new language cons ruts, and is chapter, yor learn the new features included in C# 2010, You Programming. such as identifiers and keywords, data types, variable Need of C# C4 is one of the intermediate programming I also learn about the basie ‘concepts ‘onstants, expressions, and creel a languages used fo create executable program, Itis an abj programming language having many similarities to java, C++, and Visual Boe ect oriented ic. C# combines the eticeney of C+; the simple and clean object-oriented design of java, and the language simplification of Vig Basic Moreover, being an object-oriented programming language, it fully support r ts the concepts. of ‘Steeprultion inhentance, and polymorphism. In addition to its object-oriented features, CH lige various other flumures such as Language-Integrated Query (LINQ), delegates, and lambda expressions, With a wide range of features, C# becomes the integral part of NET. These features are listed as follows: 2 Mexible—Refers to the capability of CH programs of getting executed on the local system, any remote system or on the web. 2 Powerful—Refers to the ability of C# to create any type of applications, such as Word processors, spreadsheets, and even compilers for some languages. 2 Easy to use—Refers to the use of simpler code statemer operators, such as pointers and :: and > operators. D Visually oriented— Allows you to use the User Interfaces ints instead of using complex data types and NET code libraries for developing complicated and attractive & Secure—Enables you to protect your code and data from unwanted access and damage by using the different techniques and class libraries of NET Framework. Similar to java, C# does not use multiple inheritance and pointers (in safe/managed code) but provides oe collection at runtime. Moreover, contrary to java, C# includes the useful operations of C#, such as one oxerloading, suicerations, pre-processor directives, pointer (in unsafe/unmanaged code), and Pointers (in the form of delegates). Similar to Visual Basic, it also supports the concepts of properties. AC# pre-processor Directives 5 ae help you Pimilar to other languages, such as C and C++, C# also supports the use of preprocessor directives that helP to interact with the compilation process. Remember that, in C# there is no separate pa ety therefore the term preprocessor directive is not entirely accurate. In reality, this term is used to mal phase of the compiler. The preprocessor directive allow you to conditions, and to define distinct reg directives in Ci is also prefixed with th dd warning conditionally skip sections of the sources, to report ee ae a sions of source code. Similar to C and C++ languages, the P? he hash sign (#), Cit includes the following pre-processor directives: G Adefine and #undef —Define and undefine the conditional compilation symbols, respectively: 2 AiL, elif, Helse, and #endif—Allow you to conditionally skip sections of source code. 2 Mine—Helps you to control line numbers emitted for errors and warnings, 2 fervor and #warning — Issues errors and wamings, respectively @ #region and #endregion— Allows you to explicitly mark sections of source code. 360Introducing C# 2010 jpakon the following expression to view the declaration of a pre-processor directive: PMNs oe SPR gui ten, ication, a pre-processor directive always takes a separate line of code beginning with the ih is followed by the pre-processoe directive name. Pre-processor directives are not aay as wor the C# syntactic grammar, However, you can use the pre-processor directives to include or exclude atures Of C# 2010 je F - Ss Sc eat eee “i ort for dynamic data type Named and optional arguments Access to Office Interop objects Indexed properties in COM Interop programming. Covariance and Contravariance New command-line compiler options supp’ i Q a Q a a a ‘2. Implicit line continuations let's discuss all these new features one by one. Support for Dynamic Data Type The dynamic data type, introduced in C# 2010, allows you to assign data in a variable at runtime. You can define ihis data type by using the keyword, dynamic, in the code. A variable of the dynamic data type can be initialized by any type of data, such as numbers, float values, or string data. The following examples show the use of dynamic data types: //example 1 dynamic intvar = 10; Response.writeCintvar); //example 2 dynamic floatvar = 3.7; Response.write(Floatvar) ; //Example 3 dynamic strint a ised name Stringvar = “oynanicstring"t Aten Ponse.write(stringvar: Y dynamic keyword assigns the data at runtime; therefore, it can be with COM or Jave ipt, which have runti ntime properties, Nam lec . “" a and Optional Arguments i tat 2010, you can invoke methods of a class with named|and options) arguments, These sreumens 5m hence ths oir ae lared as nor 7 they are initialized with default values. If you do not Provide ,'S Rotmal arguments with the exception that they ef aun 2 Value for an optional argument, it invokes its default valle ‘You can manually invoke a nam he fone? Passing a value by manually invoking its names stayin code snippet shows an example of optional and named parameters: (UES string infocstring name, string name + "\t" + email+"\t"* a oe {2%C void main(seringf] args)Chapter 10 ait system.console.writetine(info("Garima”, phone: "8568487")); //Line® Pe are calling ) apet, a method, called Info is taking three parameters: . a In the preceding code snippet, a method. iB Pe SKS Cra nd png crs are haying default values and can work as optional paray cemail and phone parameters are having d ae ~ Tine, marked ss Line 1s passing the value of name parameter only; however, it shows the cue com Garima —
[email protected]
0000000 = P ed The email and phone are optional parameters, whose values may or may not be sonmvented line. marked as Line 2, the values for name and email parameters are passed, pve a The output of Linge Garima
[email protected]
0000000 In the preceding example, phone number is an optional parameter and showing its default value, while am Se one flex rates dad crnal porantebae: Wow, in ie last coonmiengedll nee eee as Line 3, Hee Values name and phone parameters are passed. The output of the Line 3 is as follows: tes for
[email protected]
8568487 ‘ The preceding output shows default value for email and provides values of name and phone param. — case, the name parameter is mandatory, email is optional, and phone is the named parameter. Toleam more about the named and optional parameters refer Chapter 11: Namespaces, Classes, Objects, and STiaw Access to Office Interop Objects C# 2010 has introduced Office Interop objects that help you to access the Application Programming Interface (API) objects. For example, you need to add the Microsoft.Office.Interop.Word and icresoft Office. Interop.Excel references to your program to access the features of Microsoft Word or Excel applications. The following example shows the directives that can be included to access the office API objects using Excel = Microsoft.office.interop.excel; using word = Microsoft.office. Interop.word; Using Indexed Properties in COM Interop Programming ln the earlier versions of C#, you can access methods as properties only if the following conditions are met The get() method should not be having any parameters 3 The set() metho:t must have one and only one value parameter aever all COM properties do not fulfil the preceding conditions. For instance, the Excel -Range PCPS? has a get accessor that requires a range parameter. To access the Excel .Range property, you need to 3et_Fange() method in the following code snippet \ar/mewexcelApp = new Exce] .Application() ; : Erie pee rangeinexcel = newexcelApp.get_range("Al", Type.Missing); ippet: mcf 2m10, you can access the Excel.Range Range property, as shown in the following code snippet re mewexcelapp = new Excel .Application(); Excel Range ran '9einexcel = newexcelapp.Range["AL" do this: You need to give two arguments to a yee F sxcel Range object: TO is youneed che use hese een alue to the Value property of the Excel-Range 078° pets ora different property, Value2. The following y of the Range object: Ssing, "Range Name") ; nge_Nane’ hhow to assign values to the value propert rangeinexce}.set_val) yon Set_Value(type.wj) rangeinexcel.Value2 = 362Introducing C# 2010 joo set the values of the Value property of the Excel Range abject as flows: vynexcel Value = "RangelName”) rx, code snippet shows how to set the values ofthe Value property by using indexed parameters scat range se precdin covariance and Contravariance 0 rer xpport for covariance and contravariance in C# 2010 facilitates implicit type safe canversions for array Iv wi Tegate types, and generic type arguments, Using covariance, you can always assign a smaller type to a be type, such as assigning a decimal type to an object type. While with contravariance, the assignment bre ity that i preserved in covariance is totally revered, For instance, you can treat an object type as 2 decimal type by assigning covariance to a decimal type. You can use the out keyword to implement covariance, ioe keyword is used for implementing contravariance. while in hn concept of generic type was introduced in C# 2.0 so that the binding of a type (declared as a generic type) 10 a dala type Ie ve deterred until generic type is not used. Classes, methods, events, delegates, and interfaces can be declared and defined js genaric. Generic type helps to enhance performance, promote code reusability, and type-safely. New Command-Line Compiler Options You can always compile and run C# applications from command-line. The C# compiler typically generates executable (,exe) files and dynamic link libraries (dll) files. Besides the various command-line compiler options available in C#, the new version introduces a new command-line compiler option called /langversion. If you use the /langversion option, the compiler allows you to execute the syntax that is valid for a specified version of C# In addition, by using the /appconfig compiler option, a C# application can provide the location of application configuration file of an assembly to the compiler. t You can get more help on command-line options by typing csc -help on the command-line. Next, let's learn about implicit line continuations. Implicit Line Continuations There may be situations where you might need to continue a single statement over multiple lines. In such “tuations, you can implicitly continue a statement in the next line, as shown in the following code snippet: Console.writetine( Now alSulateareaClength: 10, breadth: 5)); ‘let's create a simple console application in C# 2010. res : sila ‘Sating a Simple C# 2010 Console Application io Q learn to create a C# 2010 Console application, named HelloWerid (also available in the CD). To create ‘olor 1d application, perform the following steps: 1 Open Visual Studio 2010 IDE by selecting Start >All Programs Microsoft Visual Studio 2010>Microsoft ‘sual Studio 2010. 3, Sl€ct File->New-Project on the menu bar. The New Project dialog box opens (Figure 10.1). Atlect Visual C#->Windows option from the Installed Templates pane and then select Console Application template from the middle pane. Enter a name, for instance HelioWorid in the Name text box. Enter a ‘cation for the application in the Location combo box using the Browse button, as shown in Figure 10.1:Chapter 10 Figure 10.1: Selecting the Console Application Template the OK button to create a new Console application in Visual C# 2010, The s the Console application, as shown in Figure 10.2: Visual Studio 2010 IDE Figure 10.2: Creating a New Console Application Add the code given in Listing 10. to the Progran. cs file of y Listing 10.1: Creating Hello Worl namespace Hel |oworld pur application Id Program class Program public staric void main(stringt] args) System. Console. writeLine("Hel1o world System.Console,Readi ine() J } Listing 10.1 shows a standard C# applic output window 364 ation that simply prints the literal string He 1 1¢ sale porta to neo at: Introducing C# 2010 application, you can see that the entire program is wrapped in the In ee contains a class called Program, which in tum contains a this na ast be declared as static, as it does not require any object for cal that the program given in Listing 10.1 can also be written by including the using statement, which is used mespaces in your applications, as follows: Namespace HelloWorld statement. method called Main(). The Main() ling. Note fp import na using systems * z se preceding example uses the WriteLine() method of the Console class, which is placed inside the “fim namespace in the NET Framework library. However, in our application, we have used the fully saifed name of the WriteLine() method, System. Console.Writaline() ; instead of using the vg atatement to import the System namespace. you can also write the WriteLine() method by placing the using statement at the beginning of the code as follows’ console.WriteLine("Hello World”); 6, Run the application by pressing the F5 key. The output of the application is shown in Figure 103: Figure 10.3: Creating a Simple Console Application Identifiers and Keywords In Ce, an identifier is a sequence of characters used to identify a variable, constant, or any user-defined Programming element, An identifier starts with a letter or an underscore and ends with a character. C# \entifiers are case sensitive; which means, the variable names sum, Sum, and SUM all three are different from cach other. For the naming conventions of identifiers, Microsoft suggests to use the Hungarian and CamelBack “otations. It represents an identifier in initial lowercase letter followed by initial capital letter for the subsequent ‘words in the iclentifier, for example, nyFirstProgran. You must remember the following rules while creating an identifier: 2 An identifier must begin either with a letter or an underscore (_) © Anidentifier can have leters, digits, and underscores 2 An identifier must not be a reserved word (keyword in C#) re An identifier must be a complete word without any blank spaces Ywords are the reserved words whose meanings are predefined to the C# compiler. In other words, keywords A those words, which are reserved by the C# compiler to be used for a specific task. You cannot use keywords 8 variaby _ le, methods, and properties because they are already defined to the compiler to perform specific canctionalities. If you want to use the keywords as identifiers, prefix the keyword with @ character. C# provides Mant identifiers having special meaning in the context of code, such as get and set, but they are not reserved ce NOds. These identifiers are known as contextual keywords. Table 10.1 lists the different reserved and esta keywords available in C# Fat 10.1: Showing the Reserved and Contextual Keywords in CH as base bool class [const double [ else aise finallyimplicit interface | internal operator public readonly sizeot stackalloe throw true unsafe Zata Types, Variables, and Constants C# supports a rich and varied selection of data types, from built- defined types, such as enumerations, types. When dealing with these data 2 Allvariables, 2 All variables declared The other important thin; ‘organizational structures: in types, such as integers or strings, to we- structures, and classes. The C# language provides a rich set of builtindaa types, you must remember the following points: ‘whether user-defined or intrinsic (built-in), can be used as objects anywhere in a program 3 2 program are automatically initialized to default values by the system when they raat single % 10 remember about C# variables is that they are categorized into three D Value Types Reference Types 2 Pointer Types ® A that mast alae Types are variables that can be assi Tyrer igned a value directly. Reference Types lance, @ interfaced through methods or functions Ke nccese their internal data. In object-oriented (sca inthis Type supports Guts hiding, and Value Type does not. Refacre nV pes/afelalee Na eeiclentiey a eference variables may refer to tf SM ee meee Pie same object, whereas Value Types are alway: type for both Value and Ref unchangeable sequence of U pat “racters contained within double quotes. and referer mers : ea Pointer Types in C# offer the same Spabilities as offered by C and C+ languages. Both, Bot ‘and poi are Ape” niin but the difference is that references are tracked by the garbage °°! is? ngs atest eater ees oberatons on pelican eee the vate con ee pend t's deal with the data values and the memory dee os of ite ae ze de on its data ty d for the vari valu ype are diferent: Constants re the qe Bale ae Bs oe eerie These lunchanged throughout the execution off Foye ea jes and constants this chapter. gram. You learn about variablesTypes pes B yale value vf have the same alae val local able 10. a special 7 Showing the Value Types in C# 2010 Introducing C# 2010 ‘allow you to store the data directly into the variable. They are derived from System. ValueType | behavior in Common Language Runtime (CLR). The value types and their content are stored tion in memory. The default values of value types are stored on stack. Table 10.2 lists the ue types in C# 2010: Represents a Boolean value True or False Represents 8-bit unsigned integer type Oto 255 F" Represents single 16-bit Character type, 2 | U+0000to U+fiff char value is a Unicode character Jmmat | Represents 128-bit Precise decimal type | (7.9x10%t07.9x10™) / (10°"™) with 28-29 significant digits Fonte [Represents 64-bit Double-precision 50x10 t0417 x10 iol floating-point type float Represents 32-bit Single-precision floating. | 4% 10%to +3.4% 10" ___| point type int ‘Represents 32-bit signed integer type -2,147 483,648 to 2,147 483,647 Tong, Represents 64-bit signed integer type -9,223,372,036 854,775,808 to 9.223372,036.854,775,807 sbyte ~ [Represents 8-bit signed integer type. short Represents 16-bit signed integer type int ‘Represents 32-bit unsigned integer type Oto 4,294,967,295 slong Represents 64-bit unsigned integer type (0 to 18,446,744,073,709,551,615 ‘short Represents 16-bit unsigned integer type (01065535 ‘The value types Struct type @ Enum type Let's discuss the: Struct Type are divided into the following categories: se in detail, Struct types are a special form of classes having the properties of value types. As you know that the value types ‘te stored on and created ef struct ty a stude consta eclared as prot only when they Yeu can create Variable, th “Ssigning a the stack; inherently the struct types Pes encapsulate small group of related variables, nts, and fields. While creating the struct type, tected as they fal to support inheritance. he variable holds the value of the struct ot null value to it. The following code snippet shows how to create a struct type: are declared as const or static: are also stored on the stack. The struct types can be copied ficiently, as stacks are the efficient and convenient means of storing and accessing the types. The such as the name, rollno, age, classname, and section of lent. They can contain constructors, methods, properties, operators, events, nested types, indexers, you should remember that struct members cannot be ‘Under the struct declaration, the fields can be initialized struct types by using the struct keyword. When you create a struct object and assign it to a Public struct student ‘int rorine mt classname; Mt section; ee s/fields //merhods ject. You can also use a struct type as a nullable type byChapter 10 — //properties
Variables r tod ° 77 variables inthe preceding syntax, T is underlying type of the Nullable type. T can be a Value Type, such as int, float, seeeeruct, however, it cannot be a Reference Type. For example, int? is the Nullable type for type int. In this example, int is the underlying type and ? is the Boolean null indicator. Similarly, float? Is the Nullable type for ‘Value Type float. The Value Type for which you want to create a Nullable type cannot be a Nullable Value Type Now, let's create a new C# 2010 Console application, named TypeMaxandMin (also available in the CD) by performing the steps given in the heading, Creating a Simple C# 2010 Console Application, earlier in this chapter, to learn how to determine minimum and maximum values of Value data types. After creating the application, add the code, shown in Listing 102, in the Program.cs file of the TypeMaxandMin application: Listing 10.2: Showing the Code for the Program.cs File of the TypeMaxandMin Application using system; using System.collections.Generic} using System. Lin using System. Text; namespace Typewaxandin Glass Program static void wain(string[] args) // First, print out the minimum values Console.writeline("system Minimums\n") ; Console.writetine("minseyte {0}", System.SByte.Minvalue) ; Console.writet: neyte (0}",” System.Byte.Minvalue) ; Console.writeLine("Minintié {0}", System. Inti6.minvalue) Console .writeLine("Minurnti6 {0}", system.Uint16.Minvalue) Console.writet: , system. int32.Minvalue) Console.write 4 System.urnt32..Minvalu Console.writet ine! system. Inté4 .winvalue Console-writet ine! System. UINt64. Min Console.writeLine("Minchar {0}". System. char-Minvalue) Console.writeLine("Minsingle {0}", Systen.Single.Minvalue) ; Console.writeLine("Mindouble {0}", System.Double.Minvalue); Console .writeLine(’Mindecima) {0)", system.Decimal .Minvalue); Console-writeLine(”\nsystem Maximums\n"); Console -writet ine('Maxsayte {0}", System.SByte.Maxvalue) ; Console-writetine("NaxByte (0}", system.Byte.Maxvalue) ; Console.writetine("Maxinti6 {0}", System. Int16.maxvalue) ; Console writeline(’MaxuInt16 {0}", System.UInt16.Maxvalu Console.writeLine(’Maxint32_{0}", System. Int32.Maxvalue) ; Console writeLine(Maxurnt32 (0}", system.Uznt32.Maxvalue) ; feLine("Maxinté4 {0}, System. Int64,Maxvalue) ; faxuintes (O}", System.UInt64.Maxvalue) ; Console.writeLine("Maxchar {0}", System. Char.Maxvalue) ; Console.writeLine(’Maxsingle {0}", system-Single.MaxValue) ; Console.writeLine(’Maxoouble {Q}"", System.Oouble.Maxvalue) ; Console writeLine(’Maxbecimal {0}", System.Decimal .Maxvalue) ; y console Read ine:a Chaptor 10 eee 12, we have used the MinValue() and MaxValue() methods to displa = ae carious data types. The output of Listing 10.2 is shown in Figure 10.4, values of the various data types. Figure 10.4: Showing the Output of the TypeMaxandMin Application Enumeration Type Enumerations are the user-defined integer data types that are declared using the enum keyword, Using enumeration, you can define a set of named integral constants that can be assigned to a variable. For example, you might have a program that models a traffic light. Traffic lights have three possible states—the green light indicating go, the yellow light indicating get prepared to stop, and the red light indicating stop. A traffic light can have only one of these states at a time, implying that the traffic light can be only red, yellow, or green ata time. In such a case, you can define enumeration ty pe variable and assign 3 values to it. The following code snippet shows how to create enumeration type: enum TrafFictight {Red,Green, Yellow}; rite To use the enumerated type, you need to declare a variable of the new enumeration type, as shown following code snippet: Trafficlight tl: The TrafficLight enume can take ation can take any of the three values, Red, Green, and Yellow; i.e. cuneate only those values that are defined while creating the enumeration type, as shown in the following code U1 = Traffictight.red; : tl = Traffictight.creen; tl = Traffictight.Yellon; Enumerations, by default, begin with the value entering a different value for the gpm Traffic. ight e by ify this value of 0 for the first entry. However, you can modify th first entry, as shown in the following code snipp Red=1,Green,Yellow istin The reason is that a traffic light, as mention, 7 the enumeration itself. CH is not pei may encounter when working with that ex wd before, is a bound value. It can take only those Valves Oo yo "fect while implementing enumerations. Here are a few o! enumerations: i er valde First, the enumeration type does not know how to display itself as anything other than the INE ayed Teun i, That Te pala atl erases ae eee you see the value on the console of form, reread 2 Enumerations do not allow you to assign iny nothing more than a wrapper around an inte you can write something as t1=(TrafficLight)4 course, but the compiler does not catch the inv, alid values to a type. However, because © er and the integer type can be cast to anything in your code and have it work. It does not ™ ‘lid cast. 370 eeIntroducing C# 2010 rations are strongly typed constants, which allow you to assign symbolic names to integral values, The pnumet gly typed means that enumerations of one type cannot be assigned to enumeration of another type ‘ough the values of their members are same. You can assign only legitimate values to the enumerations even your code easy 0 maintain. While assigning an acceptable range of values to enumeration, if you try gata” tne value that is out of the acceptable range in the other part of the code, an error occurs. As 1 a8 ons are value type, they cannot inherit or be inherited from one enumeration to another. Note that the cnumer ons are created using the enum keyword, which is an alias for the Systen.£num class. Now, let's enue ew C# 2010 Console application, named fnuneration (also available in the CD) by performing the aru given in the heading, Creating a Simple C# 2010 Console Application, earlier in this chapter. The son application makes the concept of enumeration more clear. Add the code shown in Listing 103 ‘ihe ezogram. cs file of the Enumeration application, has {isting 10.3: Showing the Code for the Program.cs file of the Enumeration Application using system: 2 5 using system-Collections.Generic; Using system.Lings using system.Text; nanespace Enumeration public enum color { Red = 1, Green, yellow } class Program aoe void main(string[] args) Console.writeLine("Please select 1 for Red, 2 for Green, and 3 for Yellow"); string str = Console.ReadLine(); int colint = Int32.Parse(str); Color col = (Color)colint; switch (col) case Color.Red: Console.writeLine(™ break; case Color.Green: Console.writeLine("The selected color is Green"); break; case Color.vellow: Console.writeLine("the selected caldr 15 Yellow"); real default: Console.writeLine(” break; selected color is Red"); his number is not assigned to any color”); i Console. readtine(); } i Pibiating 103, we have created an enumeration, Color, and defined three values, Red, Green, and Yellow, to it. reepa 2 Member is initialized with 1; therefore, the value of Green and Yellow will be automatically 2 and 3, meant ely. The code ine Coa onitne creates an object of Color that is used to acces the ner of enumeration. The output of Listing 1033 is shown in Figure 105: Lee. Figure 10.5: Showing the Output of the Enumeration Application at reference types in C# Re ies S take a look 371Py ome Chapter 10 : — ae : hes d by refi to calling functions, kn also provides types that are passed by references to calling functions, known as thet fe to the obs store the reference ofthe actual data, In reference types, anh chee Pes. Vary copy mest the ok copy to which the object i referenced. The reference types use heap te sence nee instead of the actual data In C#, heap is called managed heap, as it manages and maintains the reerency addiress where the next object is to be allocated. Initially, the pointer is addressed to the heap's eed te when the first reference is created, the memory is allocated at the base address. When the Tee address, ang sn application. the garbage olector allocates memory fori in the address space just next a thee Teeth contandes to allocate memory (or all the newly created objects. The reference types can be eal object ang parts - predefined and user-defined types. egorized into typ Let's discuss predefined and user-defined types in the next sections. Pre-defined Reference Types (C# provides you some built-in reference types, which are as follows: Dynamic type 2 Object Type String Type Let's discuss about these types in detail. Dynamic Type The Dynamic Type performs the type checking of the dynamic type variable at run time instead of compile time. You can add any type of value in the dynamic type variable. This type is similar to the object type; the difference ® that the type checking of the variable of object type is performed at compile time. The following code snippet shows how to declare a dynamic type variable using the dynamic keyword: ‘Gynamic dyn = 10; CAINE am Object Type ‘he Objet Type enables you to assign values of any type to the variables of object type. Object is an alias forthe predefined =. b> ect class. The object type is the ultimate base class for the other types in Common’ De System (CTS), such as value types, reference types, predefined types, and user-defined types. All these Da enwved directly of indirectly from the object type. The object type can be assigned a value of any other Poerie 'cfore assigning a value it requires the type conversion. When a value type is converted to the object Sees prossss is Known as boxing and on the contrary, when an object type is converted to the value type, the P is soa Sai ‘The following code snippet shows the use of object type: xel5; //boxing Pre first line of the prece: in eo line of = Preceding code snippet creates a variable x of object type and the second line assigns *vanable. The process of assigning the converted value to the ‘object type is called boxing, ‘String Type ie String : : Felli, Tt String Type enables you to assign string values to the variables of string type. The string type #5 in double Quotes The sting ca the unchangeable sequence of Unicode characters contained within df of tring type, you ceanck chan ls type that is directly derived from the object type. After creating ler type, you cannot change its valuc st two forms—quoted and equal) “ali The value fra string type can be assigned using the The following code snippet shows hot shows how t string sname="c# 2010"; © 2ssign values to string types: In the preceding code snippet, sname is = pet, sname is a string variable having a value C# 2010. asteated @-quoted string literals are writte in the following code snippet. @"kogent Learning Solutions inc” in the double quotes prefixed by the @ character. This © 372 area riai AE S aiim cig daSD ht . ene a Introducing C# 2010 sont of using strings only a5 an array of characters, you can use stings to represent a string of Unicode iste You can use the string keyword to declare a string variable. Now, let's create a C# 201 i ' ? 110 Console haion, named Stxings (also available in the CD). The Strings application shows how to declare and 2Troeae atring variable. Add the code, shown Listing 104, inthe Program.cs file of the Stings application inte and initialize strings: i aing 10.4: Showing the Code to Declare and Initialize Strings ing systems ; using Gystem-Col lections..Generic; Using system.Ling; using system. Text; namespace Strings class Program static void Main(stringl] args) { string stri //oeciaring a string variable str = "Kogent Learning Solution: //initializing the string Console.writeLine("The value of the string variable is " + str): Console-ReadiineQ; » } } In Listing 10.4, we have declared and initialized a string variable named str. The output of Listing 10.4 is shown in Figure 10.6: Figure 10.6: Showing the Output Strings Application tis important to note that while initializing string variables, the values are enclosed within double quotes. If You enclose the value within single quotes, the compiler takes the value as a char and throws an error The a m. String class provides a set of different methods to manipulate strings, such as changing, the case of strings and adding two or more salokaltrings. Let’s take a case when you have hwo of Hote strings and you vats add them or you want a reverse of a particular string literal, or you want to find the length of a string, You can perform all these manipulations on strings by simply creating a string data tyPe and using the dot CPerator () to get the string functionalities. To make the concept of string clear, let's create © NaN CH 2010 ‘onsole application, named StringManipulating (also available in the CD). The StringManiputal lng *Pplication manipulates string literals using different methods. Listing 105 shows the complete code of the tee ating application 'ing 10.5: Showing the Code of the StringManipulating Application USING Syster “sing System.c i f sCoVlections.Generici using System.Ling; using System Text; t espace Stringmanipulating Glass Progran static void maincserinal] args) ring variable string fnane; //oeclaring a string vartal string frame: /oeclaring a string vartable i a string variable String Inane; //eclaring a string Varley) ZonsolecuriteLineCenter your first name )e ~~ 373fname = Console .ReadLine(); a Console.writeLine("Enter your middle name"); mnane = Console.Readtine(); : Console.writetine("Enter your Tast name" Tname = Console .ReadLine() ; Concatenating the string values string completenane = fname + "\t" + mame + "\t” + Inames e | Console.writetine(°vour complete names’ conpTetename) | Console. writel ine(” " : Console.writeLine("Your name in UPPERCASE is " + Completenane. Toupper());//Converting to UPPERCASE Console.writetine(” “ Console.writeLine("Enter the new first name with which yoo’ your previous first name"); ‘YOU NANET CORTE ake string nennane = Console. Readtine() ; Replacing string Soasale-writeline("The new name is" + conpletename. Replace (fnam Console ReadvineQ; Place(frame, newnane)); ) } ve have declared five string variables named fname, mname, Lname, conpletenane, ant s of : and name ate taken from a user as input. The completonsn = the concatenated value of ame, mame, and name variables. The method tums the case of the value in comp1etename to uppercase. Similarly, the method replaces the fname value in completename with the g 105is shown in Figure 107. Figure 10.7: Showing the Output of StringManipulating Applica User-defined Reference Types be ‘defined refer “ie Neha jetined by using pre-defined types. User-defined reference ‘YP uur parts which as follows: Interfaces a a D Delegates Q Array Now, let's discuss about these types in detail starting with classes, asses es derived from @ im in the 5 -_ In C#, all classes are user-defined dat, base class, called sy m. Ob e . 'yPes and are considered as objects. All objects are defines all the objects to the system and treats the! 374Introducing C# 2010 object to a function, you can find out what kind of object you are dealing with by using them based on a class. Unlike C++ or C, you cannot have a simple function that acts on its ons in C#f are ¢ ications contain a single static method, called Main. Listing 10.6 shows the code of a pplicati ula? “Cw Console appli owt pasic C# application: inabi ; a
? tm Losing NO. we have created a delegate named IntDelegate, Next, we have declared a variable, de) tuys Sete agate, aamigned new object to it and invoked the delegate by passing the SquareNamg) mat Cabcatr lana [& Getal i» Chapter 13 Pointers, Delegates, and Events of the book. was \9 so) © sed f© ore the number of elements or variables of the same data type at contiguous memory ‘cotens © as ondened manner. Similar to other programming languages, C# also support arrays of Value Types soe Reserence Types but in Cf, arrays cannot be created on the stack. This means you cannot create an array Sema) © s method as you would in C++ or java, In these languages, you can write the following code to create ae. arn pees 3 Tanai = 5 freonding cade would create a static array of 10 elements, each of which is properly sized to bold Sipe © CH the array is an actual type, much like integers. Arrays must be allocated on the heap: following line the equrvalent array ‘statement in C# of the preceding C++ or java code line: a Seu) x + mew tntt20); ae + you can see, an array is mach more than a simple modifier, as it would be in C++ or java. ree he Bettas abject, fost as all other types are in C#, you can also inspect them for certain attributes. 1" coe Thar anibwte i the size of the array, which specifies the number of elements that can be ee ay ~— fe leet ne Stained by using the Length property. You can access the length of $90 Ven = x.Lengen: Cit also supports multi-dimensional tes the old-style FORTRAN, in an array definition) Unlike C++ or av ‘arrays, which must be allocated on the heap as well. delimited dimers “7% for declaring multiple dimensions (by having comma: The preceding code produces the follow! This is certainly useful bec Tower and upr ly useful because inthis, you knoe the ss bounds of an array is difficult. f ” Se oa fae Wemay ak deen, the array ‘ing output 376and GetUpperBound(). For Example, you can find out the hound bo sea py writing the following code: Poanticies of tie, preopding five arma 1 f sole.WriteLine("Lower Bound ={0}, Upper sound ={1}" system Pye cetupperBound(O)); ind =(1}", fivebyfive.GetLowersound(0), es the following output: code produc co Pound = O¥ Upper Bound = __ toe ned earlier, CH supports both single-dimensional and multi-dimensional arrays. In both the cases, the dynamic. C# has no notion of a simple static array, which you might find in C or C SD i i it oe ++, The single- oN al arrays are indexed by a single integer; whereas, multidimensional arrays are indexed by ae vrs, Now, let's create two C# 2010 Console applications, named SingleDimension ees ionArray (also available in the CD) to learn how to declare single-dimensional and muli- jcional arrays. Add the code, shown in Listing 108, in the er cs file of the ionArray application: Listing 10.8: Showing the Code for the Program.cs File of the SingleDimensionArray Application using systems sing system:Collections Generic; Using System. Ling; sing system. Text; namespace SingleDimensionarray ( lass Program gtatic void main(stringl] args) string(] name = new string(2); int{] subl = new int(2]; int[] sub2 = new int(2) int{]_total=new int(2 fon Gint 1-0; 1<-1; i++) Console.writeLine("Enter the " + (i + 1) + “student name"); name[1]=Console.ReadLine( ; < Console.writeLine("enter the marks of first subject"); ‘subi [i] = int.Parse(console.ReadLineQ, . Console.writeLine("enter the marks of second subject"); Sub2[i] = int, parse (Console. ReadtineO): total (i]=sub1(i]}+sub2 [i]; for Cint i = 0; i <= 1; i++) console.writeLine("the student name is" + mame[i] +” and his total marks is “ stotal li]: Console.ReadLine(); > } The o ‘“tPUt of Listing 10.8 is shown in Figure 108: Tan Bo Fmt 2 Figure 10.8: Showing the Output of the SingleDimensionArray Application 377
d re erty ation to understand the nullable type conversion, Program.cs file vy Listing 10.12: Showing Coste for the Nullable Type Conversion using System: sing System. collections Generic: using Systes. Ling: sing System, Text: namespace Nu} lableConversion i class Program { Static void ain(string(] args) i int m= 123; //assigning int? a= m; Console.writeLine("the value of a is " (fasstgning value of nullable integer v; variable double? b = a; Console.writeLine("The value of nuliat (/caverting nullable double to nulla e value of integer variable m to nullable integer varian), ee +a); ‘ariable to nullable double Pie double variable is "4 5); ue to = » ible int and assigning th nullable integer variaby i ey int? c = Cint?)b; Frenne reriteLine('the value of nullable integer variable ie « +0; (Aeaayecting nullable int to integer type and assigning waloe tt integer Variable int n= Gint)e; Censote-writeLine("the value of integer variable is “+ n): Console. Readt ine(); We tans {cclared a variable, m, of integer data type and assigned a value of 123 to it, whichis the nullable variable a The data types of both these variables are same; therefore, a 4 =sion. The code line double? b=a assigns the value of a to a nullable double iat ie € type. Note that when we assign the value of nullable variable b to the nullable inte 3 y converted to the Pe conversion is required, because the double type cannot be implicitly re ie Pana eget type. Finally, we convert the nullable integer type to integer type. The output of Listing Figure 10.13: Showing the Output of the NullableConversion Application Boxing and Unboxing | Boxing and unboxin the two maje situations a link be CH type system. They are used to ee: _ but in nce type. All value types are per re, you ca rence types are stored in heap; therefore’ Y 2 Pe. This conversion is called boring ve, The com ie (Centers when a value type is converted into a base object or an interfac on heap ™ intime (CLR) converts the value type 'o reference type. CLR allocates memory °° 384 | ig are important conce data types in C#—value they need to be refer type into reference ty ts used in the type and refere Pscar enced as heap. As refe Boxing is req Language RutIntroducing Cit 2010 es the value type instance to it Boxing is an expensive process, since it copies an object from a stack to a cs Me equires a number of processor cycles as well as space onthe heap, Another disadvantage of using eat the same object appears at wo different places in memary which can have contradictory sates vponing isthe process of Weta Bene ue een res ee value type. This is done unborn sing unboxing, The following code snippet shows how boxing is done impliity; whereas expe has to be done explicitly by using type cast: aot y_2i23i //avalue\ type ieee obj = yi //boxing is implicit nt Zi ve) obj: //unboxing fs explicit (use of type cast to unbox) Variables ariable isan identifier that denotes a storage location in memory. It stores numeric or string values that might vi during the program execution. A variable may take different values at diferent ies during the Chany of» program but the name of the variable always remains same. Every variable has 2 data ype that «xeeines the type of values you can store in a variable. The following code snippet illustrates how to declare and assign a value to a variable: int 15 j=15; In the first line of the preceding code snippet, we declare a variable named i of the integer type by specifying a data type of int. In the second line, we assign a value of 15 to the i integer variable by using the = operator ‘A variable can be declared as local or class variable. Local variables exist within the scope of a given ‘method in a class; whereas, class variables exist for the entire lifetime of the object instance of a class. Class variables can be used in any method of a class and can be public, private, or protected. Local variables cannot be defined as public or private because they are not accessible outside the method in which they are defined. ey ey Cit also provides static class variables, which can be used in static class methods. A single instance of the static class variable exists for all instances of a given class. Variables can be of array types. The following code snippet shows how to declare an array of integer type: int{] arr = new int{l0}s Variables, however, ae not restricted to simple Value Types or arrays of those Value Types. You can also define aa that are user-defined types. For example, you can create an enumeration, as we have discussed earlier is chapter. Alternatively, you can create a class instance (object) by writing the following: wn ggho f= news ROBO: n ny et you can even create an array of enumerations or objects similar to this: Tratfictight{} tla= new TrafficLight(10}; as rere fooarray = new Foo[10]; ae line creates an array of an enumerated type. The second line of the code seems to create an array of Site, But in fact, it just reserves a block of memory that is big enough to hold 10 Foo objects. To create them you would do something similar to the following code: O04 fooarray = new Fooll0]; For Cint f<05 110; +4) : {ooarrayti} = new Foo) ieee as create all the array elements, the program crashes as soon as you try to access the actual objects i . 'y because they are not yet initialized. cones inte : ec a new C# 2010 Console application named DeclaringVariable (also available in the CD) conn 2pplication, you can see how to declare a variable, assign ta value, and then print the result to the output ieee ects 10114 chow the declarations of three simple Value Types in the application: ing 10.14: Showing the Code of the Program.cs File Using system; Using system.collections.ceneric: Ikyo using system. Text: wamespace Declaringvariable 385 | -.____Chapter 10 = — t class Program ; static void Main(string(] args) ie h. ee {/oeclaring short type variable int y; //oeclaring integer type variable double 2; //Declaring double type variable x= 6 y = 10; zextys : Console.writeLine("x = {0}, Y= {1}, z= {2}", x, y, 2): console. ReadLine() ; ) ) } Int ing 10.14, we have declared some variables, assigned values to them, alled the ©() method of the System output of Listing 10.14 is shown in Figure 10.14 and then print the result. W. ie have “Console object to display the values of the variab les. The Sa Figure 10.14: Displaying the Output of DeclaringVariable Application ' you can also declare the Nullable type variables. After the declaration, you can assign pean Tange of values as well as a null value to a nullable type. These values are specified for the Cay eae of the nullable type. For example, you can assign a value from -2147483648 to 214748364 eer re Fst32> (pronounced as nullable of Int32). You can assign the values true, SE tet To understand this concept better, let’s create a new C# 2010 Console See chown “fyBee (also available in the CD). After creating the NullableTypes application, a in Listing 10.15, in the Program.cs file: Listing 10.15: Showing the using systen; using System. collections.ceneric; using System.Ling; using System. Text; namespace Nullabletypes { Similarly Code for the Program.cs File of NullableTypes Application class Program { static void Main(stringl] args) { iat? vard = mull: //oeclaring nullable type variable int var2 = 5; varl = var2;\ //valid // ink? is nullable where under is int if (varl.nasv. ee { alue = true) Sucthe wr ttel i Sard’ 2° yi tarsaye uk else { Console.writeLineC'varl = wut"); Console. ReadLine(); 386 area Se METIntroducing C#t 2010 r ate 10.15, the value of vari is printed as 5 on the console. This is because the value of var2 is assigned a if no vale ie Aesiones the output will be displayed as va 11, The HasValue to perty POY ided by nullable types checks the value of the null variable. The output of Listing 10.15 is shown in prope 10.15: Figure Figure 10.15: Showing the Output of the NullableTypes Application once you declared a variable, you must initialize it with some value. Variables can be initialized in several oe et the time they are declared, within the application with a fixed value, or by copying the value of “over variable into them. Now, le’s create a new CH 2010 Console application, named snot izingvariable (also available in the CD. After creating the Tat ializingVariable application, tthe code, chown in Listing 10.16, in its Program.cs file to initialize variables: Listing 10.16: Showing the Code for the Program.cs File using system; using system.collections.Generic; using System.Ling; using System, Text; namespace Intializingvariable t cesses oe main(stringl] args) // initialize a variable at declaration short x = 53 7/ initialize a variable as a copy of another int y = x double z = y + 10.25; //assigning an integer value with a Floating-point value Ste a CinO2; // converting the floating-point number to integer Console.writeLineC"x = {0} ¥ = {1} Z= {2}", % ¥, Di Console-writeLine("A = {0}", a); y Consele:ReadtineO: + * In Listin, ae 10.16, we have assigned the sum of an integer value and a floating-point value to a floating-point atabe. Next, we have converted the floating-point number to an integer. This conversion requires an explicit cause it can lose precision during execution. Suppo: SubPose that you had written the statement, 4 ode snippet: int a= 2 21, of Listing 10.16, as shown in the following When yo can aus uw run the application with the preceding code snippet, the compiler would generate an error message ot implicitly con tyoe ‘double’ to ‘int’, By forcing you to specifically cast the floating: Poin 1B Pe fang thumber to an integer, the compiler ensures that you understand the consequences of your actions. It is thar) overestimate the number of occasions in which invalid conversions in applications have introduced bugs ‘aused serious damage and were difficult to track down. The ou Output of Listing 10.16 is shown in Figure 10.16: 387 aChapter 10 Figure 10.18: Showing the Output of the InitializingVariable Application esse specific scope. The scope of a variable determy ts and variables can be accessed only within the specil aoe fess vite fn proguazr where the var seen beeeseer emer The scope is of two types Wd flan Joa daclire u variable within Coe TOISEES REST at Bes local Scope ora Beek att ES local variable, The variable having a local scope cannot be used outside a code block in therefore itis known as local varia 2 ‘ href you declare a variable outside the code block (or before defining the Maing method), the Seshich mit haves Oat scope and known as global variable. Such a variable can be used throughout the Listing 10.17 shows an example to illustrate the scope of variables: program. Listing 10.17 shows a : Listing 10.17: Showing an Example for the Scope of Variables class Scope ebuicl tia Scopel() Public void Scope2() C Console.writetineCi); ? ¥ tn Listing 1017, variable iis declared and initialized within the Scopel() method. Now when you try to access i in the arable i outside the Scopel() method, a compile-time error occurs stating that the name i does not exis ; id can be sero Skt. This is due to the reason that the i variable is a local variable of the Scope () method an bbe accessed only within this method. The class scope uses the access modifiers, such as © keyword makes a variable local to a clas Outside the class in which itis This makes the variable to be understand the scope rivate and public, to specify the scope of a ee s and specifies that the variable cannot be eee declared. You can make the variable global in the class by declaring oa used in any class within the entire program. Listing 10.18 shows an of a class: Listing 10.18: Showing an Example for the Scope of a Class PUBIC class Localscopel int i = 0; public class Localscope2 rele Scope(), ‘i Console.writeLine(i ) In Listing 1018, you can see that the variable j is declared in class LocalScopel. If you attem! outside the LocaiScopel class, the same ‘RmPile-time error occurs stating, that the name i does 70! private pdt ine er7Or has occurred because the variable is declared in the Loca1ScoP Private by default. There accessed in the Local Scope? class. ays a gore C# provides an easy w of a variable by removing the need of specifying alwa" nus ol variable in your application, C# has multiple levels of Variables, including different scopes 388 ssi ccess to acces Pexist in the class and fore the variable cannot beIntroducing C# 2010 As discussed, you can declare variables at local or class level. Let's create a new C# 2010 Console yiable i variable® "named ScopingVariable (also available in the CD), After creating the application, add the code pplication i fil app z an inting 10.19 in the Programs file ofthe ScopingVariabLe application i 10.19: Showing the Code of the Program.cs File ofthe ScopingVariable Application lysing system : - using systen.collections-Genenicy ‘5h 2S" re ariable { class Program static int x= 10; Static void Main(string[] args) c // Locally defined copy of x int x int. double z = y + 10.2! int a = Cint)z // output X. Which one gets written? Console.writeLinet fo} v = {1} z= {2}", x, y. 25 Console.writeLine("A. (0. a: 7/ force the output of the class level Console.writeline("class Level x = {0} Console. ReadLine( variable Program.x); } ? 3 In Listing 10.19, the x variable is declared two times. At the first declaration, x holds the value 10 and is declared as static throughout the entire program. As x is declared outside the Main function, it acts as a global variable. However, when you declare a variable with the same name x, it acts as a local variable and does not relate to the tlobal x in any context. The scope of the x variable (int x = 5) is limited only to the Main() method. The output of Listing 10.19 is shown in Figure 10.17: igure 10.17: Showing the Output of ScopingVariable Application Constants Similar does {28 Variable, a constant is also used to store a value, However, unlike a va The gt change during the execution ofa program. A variable is declared a» constant using the lowing code snippet shows how to use constants in your application: c SONSt double e= 2.718281828459045235360287; St int x10 riable, the value of a constant const keyword. In A reer line of the preceding code snippet, we have declared a constant, ¢, of the double data ype an int dah Yale 2.718281828459045235360297 to it In the second line, we ave dele a constant oe thi pe and assigned the value 10 tot. The values assigned to these constants 4070 TS Will dsp on Of the entire program. If you try to assign ‘another value to a constant and compile the prog econ ai error stating that the left-hand side of an assignment must be a variable, ang «S'2nts are mostly used while performing the mathematical calculations here the value of e Pi availayie” © Pre-calculated. Now, let's create a new C# 2010 Console ap? code, o1® i the CD) to show how to declare and initialize the constant valu » showy ‘own in Listing 10.20, in the Program. cs file: property, or indexer ication, named » within your application. Ad 389 ee — —— SsChapter 10 Listing 10.20: Showing the Code for the Program.cs File 0: Sing ysten:colTections ceneric; Using systea.t1 cing systen, Tex hamespace Constants ass Progran simeseathe vats mincstringt) arg UY coast dale pt = 3.1472; ime Console.writeLine (“enter r= int. Parse(Consol: She double circlesrea Console.writeLine| Console-ReadLine(); ) d , 'm Listing 1020, we have declared a constant variable, sseof the const keyword states that the value ofthe p The: Figure 10.18: Showing t Expressions and Operators An expression isa set of language expressions, C# 2010 Properties, and literal, Operators play a vital role in operations on the operands The operators in C# 2000 falls unde and type testing, equality, logical A assignment, and lambda. Table 10, with their description: IND, logic {Table 1015: Showing the Operators in C¥ attrib | = Decreases the value of ‘operand (x) by 1 =] f Discovers infor [irene tog ere 1e area of ‘circle is" ‘output of Listing 1020 is shown in Figure 10.18 elements arran, Provides a complete set Fesforming some computation or other operations, Theref srefore the operator specifies the operations to + several cate S lists differ Acts the member variables and methods ofa class Asses methods and delegates ofa daw Represents s) //Peclaring constant variable the value of 1"); idLine()); + Circlesrea); pi of double data type by 'Y using the const variable is constant, ie, ew 3.1472, uae he Output of the Constants Application iged together to perform a specific task or computation. To — of language elements, such as variables, constants, operates, such as arithmetical and logic be performed inthe expr TOR a emay unary, multiplicative additive, shit eto!) XOR logical OR, conditional AND, conditional OR, aang “ent categories and the operators that fall within those cae inte “avare brackets that are used with arrays, indexers, PO es, ofits operand (x) by 1 "ution about reference and value types. ow conditions in certain operations: ‘used by overflow conditions and accepts the £€” + of the overttype testing Equality Logical AND ae Sa woltiplicative Relational and Introducing C# 2010 [eae ‘Combines pointer dereferencing and member access. Pointer dereferencing is & process used to access the value to which a pointer references. ‘Gets the logical complement ofthe negative value. ‘Gets the negation of the operand value. Tnverts the result of a Boolean expression. [|e he iy representation ofan expression. x Tncreases the value of its operand (x) by 1. It first increases the value of x by Land then assigns the increased value to it. ‘Decreases the value ofits operand (x) by 1. It first decreases the value of x by 1 and then assigns the decreased value to it. Returns the Boolean value true, indicating an expression satisfies the specified condition. Returns the Boolean value true, indicating an expression does not satisfy the specified condition. =x Returns the address of its operand. aa % Cong te ers pees eee ei ‘Computes the sum of its operands. “Computes the difference ofits operands, Shifts Ws Rist operand left by a mumber of bits specified by the second operand ‘The number of bits should be an integer value al Shifts ts frst operand right by a number of bits specified by the second operand ‘The number of bits should be an integer value Finds out whether the frst operand is less than the second operand. It returns true if the condition satisfies; otherwise, it returns false Finds out whether the first operand is larger than the second operand. Itrekims true if the condition satisfies, otherwise, returns false ‘or equal tothe second operand. It itreturns false. Finds out whether the first operand is less than returns true if the condition satisfies; otherwise, Finds out whether the firt operand is larger than or equal tothe second ‘operand, Ttretumns true if the condition satisfies; otherwise, itreturns false ‘Checks the compatibility of a variable with a given type Converts a value toa given reference type. Checks whether the wo expressions are same or not. It retums true if the expressions are equal: otherwise, itreturs false = Chis whether the Fwo expressions are stme or not, It retums tra the Sipreseions are not equal otherwise itetums fale © Tamputes the logical AND ofits Boolean operands. For integr! operands, & compre the corresponding bits of two integrals and comPuies Tm logical fice AND of the operands. It returns true ‘and only if bath its operands are 391‘Computes the logical exclusive OR ofits Boolean. one ofits operands is true ‘Compates the logical OR of its Boolean compares the corresponding bits of two bitwise OR of the operands, It returns true if, tre operands. For in integrals and cy and only if any Nel opeand OMPULES the lpia] ‘one ofits operand i Computes the logical AND of its Boolean operands, Hye ‘operand whenever necessary and returns tn aluates the song tue. wif and only. 392 Tooth its operands ar ‘operands. It evaluates the second and only if any of ts operands is tre Returns one of the two values based on the result produced by the Boolean expression Computes the logical OR of its Boolean whenever necessary and retums true if Assigns a value toa variable, property, oF indexer Assigns the result of the difference of t operand. Assigns the result of the product of the first operand Assigns the result of division of the fist operand Assigns the remainder of the divi the first operand. ‘Assigns the logical AND of the operand Assigns the logical OR of the first operand the first and second operands to the is t and second operands to the fist ‘operand by second operand tothe fist ision of the first operand by second operand to first operand and second operand to the first ‘operand and second operand to the first Assigns the logical XOR of the frst operand and second operand to the fist ‘operand. ‘Assigns the left shift resull operand. Assigns the right shift result of operand, tof the first operand and second operand tothe fist he fist the first operand and second operand to th wu if calles Returns one of the twa values depending on the null values. It returns the — ered ifs value snot nul; otherwise, it returns the right operand. Ee = FalaZats the inpat variable on its eft fom the statements or expressions right _— Scope Resolution Defines the accessibility scope ofthe specified identifier Fe} value within an expression; therefore, C# pro\ Oe nen Pema OCH coarse execute the expression ina specie order. La’ tae overview of the operator precedence G P in a sp Operator Precedence With a large set of operators in CH, you can required calculations. However, the ‘ase of precedence, ie. which operation is perf {iS many of them simultaneously in an ee Feratot © Of More operators may result in conflict o med first.For this ee eS h se with 64 Purpose, Cit associates the precedenc forIntroducing C# 2010 fine the evaluation order of the expression having these operators. Operator precedence is a set of cifies the order in which the compiler evaluates an expression. The operators are associated with hat Fpression on its left or the expression ons right, which is known as the associativity ofthe operator tier he eT he precedence of the different operators in C#: aple 10. or tod Sa tunaey) 21 4% SK Tmetic), - (arithmetic) 3 Left i Left Right =a = Right In Table 10,7, the operators at the same level have equal precedence and are evaluated in the given order in an expression until and unless separated by the parenthesis. Using the ?? (Null Coalescing) Operator The null coalescing operator (22) is mostly used with the nullable value types and reference types. The 77 operator is used between two operands where the first operand must be a nullable type. The second ‘operand ‘must be of the same type as the first operand or of the type that can be implicitly converted to the first type. It ‘hecks whether the valle of the first operand is null or not. Ifthe value ofthe first operand is mull, it returns the {Rte ofthe seconal operand else retums the value ofthe first operand. Incase, if you declare the Gab scrils jute {pe that cannot be implicitly converted to the type of the first operand, a compile-time efor = BUNT mah, It's create a new C# 2010 Console application, named Nullcoalescing (alse ae eaten : a the concept of 2? operator more clear. After creating the NullCoalescing application, a x Z "in Listing 10.21 in the Program.cs file of the application to use the null coalescing Coa “ting 10.21: Showing the Code for Using the Null Coalescing Operator using system; Using S¥Stem-Collections Generic; usin System. Ling; ystem. Text: TimesPace Nuilcoalescing glass Program $tatic void main(stringl] args) nt? i = null; //nutlable variable int? j = 30; | //nullable variable int k; - k'= 4°27 25; //Using 2? operator to check for null values Console.writeLine("The value of k is " + K)i Weiaioes k = 5 7? 25; //using 77 operator to check, for pu Console.writetine("Now the value 01 +h: 393Chapter 10 Console. ReadiineQ; ) 21, we have declared two nullable variables named i and ain either the This means that the 1 nteger value or the null value. We have assigned null v, to the } variable, Using the 2? operator in the k 25 alu to thei variableand ic statement, the compiler checks whethe, 2030 is null, the value of the right operand is returne, ate it a d. Similarly in the ae which is not null, Therefore, the value assigned to the 7205: is shown in Figure 10.19: Variable, The not. As the value of ment, the value of 5 is of jis of Listing 10.2 Figure 10.19: Showing the Output of the NullCoalescing Application Using the :: (Scope Resolution) Operator The =: (scope resolution) operator is added between tw identifier of the : : operator is taken as a global identifier, operator is global, the global namespace 2010 Console application, named Alia with the global identifie © identifiers to define their scope. The lefthand an extern, or alias. When the left-hand identifier of the 's searched for the right-hand identifier. Now, let's create a new Ct Cla {also available in the CD) to show the use of the operator Usting 10.22 shows the code of the AliasClass application: Listing 10.22: Showing the Code of the 's Application using systen; sing System.Collections Generic; using System.Ling: using System Text; namespace Aliasclass i class Program € public class systen public void Print { it. of : global : :system.console.writeLine("this is an example Sperator'ys } Wass 1] Sefine a constant ‘console! const string Console = “Hello”; const string strl = “world”; {UAC void main(stringt) args) // Error accesse: System sys SYS.Print() atobal 1g¥3tem.console.writetine(console) ; Global ystem.Console.WriteLine(stri) ; ; global *System.Console-Readl ine(); S Testapp.console new system(); S % In Listing 10.22, we have used the: : operator with the application, The output of Listing 1022s shown in Fipa the Fi zjobally i" global identifier to access the identifiers & re 10.20: 394 ae Introducing C# 2010 Figure 10.20: Showing the Output of the AliasClass Application going the 'F and as Operators pe is operator checks wheiher ani objec is compatible with the given type or not and returns a Boolean result, Tes clue or false, The object may either be of the same Kype or may bbe derived from that particular given i euThe as operator converts the reference types explicitly into a specific type. If the reference type is vy patible with the specified type, it performs successful conversion; otherwise, it returns the null value. Note crne as operator does not throw an exception. Let's create a new C# 2010 Console application, named ie 2 (qlso available in the CD) to learn how to use the is and as operators Listing 1025 shows the code to itudin the Program.cs file of the IsandAs application: Listing 10.23: Showing the Code for the Isandas Application using system; using System.col? sing System. Ling using System. Text; namespace TsandAs tions .Generi glass Program ont ee main(string{] args) object i = 25; object str = “kogent Learning Solutions ee if G is string) checking compatibility Console writeLine("i is a string type"); else ‘Console.writeLine! jis an integer type"); string strl = 1 as string T7casting 1 to string string str2 = str as strin Yicasting str to string Console writeLine(*the value of stri is | + strd}i Console .writeLine("The value of str2 is "+ str2); Console Readi ine; Nae When you compile the code shown in Listing 10.23, the compiler checks the type compatibility with if (is (aay 2) ine. The compiler verifies whether the i variable is string variable or not. However, with the value Dock wt assigned to the 3 variable, compiler
Microsoft Visual Studio 2010 Microsoft Visual Stadio 2010. The Visual Studio 2010 IDE appears. Select File-> New->Projet on the menu bar, The New Projet dialog box appears (Figure 11) led Templates pane (Figure 11.1) 2 3. Steet Visual CH->Windows from the Insta 5 Select the Class Library template from the middle pane (Figure 11.1). tox In this case, we have ipped #iMlznesace Location combo box. Type a name nae ame for your application In the Name text (Figure 11. ? EE Enter the co t ication in the r the complete path ofthe folder where you want to save your application, < a hi ee fered Ds\Books\ Back Book\ NET Frammewors Jo BB\ applications\ Chapter 11\ igure 11.1) Click the OK button, as shown in Figure 111° 399 word fllowe by its name. Note at “cannot include any Access available inthe CD). 6 ~~ ieFigure 111: Selecting a Project Type from the New Project Dialog Box A s Library application with default code in the Classi. file is created, as shown in Figure 112: PP et ah J 3h ete PS ade basen S c Sy Figure 11.2: Creating a New Class Library Application es default code appearing in the Classics file of the application with the code Bi Listing 11 Listing 11.2: Show: using system; Using Systen.collections.ceneric; using System.Ling: using System. Text: namespace MyNanespace { public class myclass Public static void method) had Console.write(*r’ am using Shen Be »; the Code to Create a Namespace wamed 35 In Listi vatiaihthe name Hytiamespace, which consists of a class which Build the ™; Teen to 'ceke airway hha eae MyNamespacey consists of a class names as My 400 1.2, you have created a namesp, _4 Namespaces, Classes, Objects, and Structs w, you need to add reference of a user-defined namespace to use it in your application. Perform the following ea void references ofthe MyNanespace applicati right-click the MyNamespace solution in Solution Explorer and select the Add->New Project option from pontext menu as shown in Figure 11.3, to add a new project: Figure 11.3: Selecting the New Project Option Select Console Application from the middle pane of the Add New Project dialog box. Enter ReferenceAppl ication (also available in the CD) in the Name text box of the Add New Project dialog box and click the OK button to create the application. 4. Right-click the Referenceapplication project in Solution Explorer, and select the Add Reference option, as shown in Figure 11.4: Figure 11.4: Adding a Reference The 1" Add Reference dialog box opens (Figure 11.5) Select the Projects tab to view the project name: If the name isnot displaying there, then locate the path the project through the Browse tab and click the OK button, as shown in Figure 11.5 401 aie ig were aaa OeChapter 11 Figure 11.5: Adding a Reference to the Namespace Now, the reference of your namespace is added to your application. After adding reference of the namespace to your application, you can use keyword, followed by the name of the nami the namespace. To do so, ace through the directive in the Ref. you mus espace. Listing 11.3 shows how to access a predefined erenceApplication example: Listing 11.3: Showing the Code of the ReferenceApplication Application using system; | using Systen.collections .ceneri using System-Ling; using system.Text: using MyNamespace; namespace Referenceapplication { class Program { static void Main(strina(} args) { MyClass. myethod(); Console.Write("\n\nPress ENTER to quit Console.Readtine(); ) ? In Listing 11.3, we have added the user-defi Now, run the application by pressing F5. 7 i de, ined namespace, MyNamespace, and used its members in the co application: ication Figure 11.6 shows the output of the ReferenceApplical Figure 11.6: Showing the Output of the ReferenceApplication Application a Before running the MyNamespace application, you should set the ReferenceApplication application as the startup Pro The System Namespace The following are some ofthe common namespaces provide, _ system— Contains the important an, events, event handlers, inter cd by the NET Framework class library: used 4: it allow you to work with commonly- -ptions, ata tyPe id base classes that faces, attributes, and exce 402 ala coco Qo o . Namespaces, Classes, Objects, and Structs cyoten-conlections—Includes interfaces and classes that define various collections of objets 5 ling list, queUeS arrays hash ables, and dictionaries qyoten. bata clades] asa ee ee with multiple distributed data sources. cy aeem.Data.01eD Includes classes that support the OLE DB NET data provider. «seem Data .Sq1C1Lient — Includes classes that support the SQL Server NET data provider. rem .Data .OracleClient—Includes classes to implement the data provider for Oracle. Gystem-Data.odbc—Includes classes to implement the data provider for Open connectivity (ODBC). cysten. Diagnostics—Includes classes that allow you to debug your application and to step through code while debugging it. It also includes methods to start system processes, read and write in event Jogs, and monitor system performance. system, Drawing—Provides access to the GDI+ graphics functionality. More advanced functionality is provided in. the SystemDrawingDrawing2D, SystemDrawingImaging, and System Drawing,Text namespaces Database system, Drawing. Drawing2D—Includes classes that support advanced two-dimensional and vector graphics, System. Drawing. Imaging—Includes classes that support advanced GDI+ imaging, System, Drawing. Printing—Includes classes that print related services for applications. system,Drawing.Text— Contains classes that help you to work with advanced GDI+ typography operations. Users can also create and use collections of fonts, by using these classes. system, Dynamic— Includes classes that are used to support Dynamic Language Runtime (DLR). systen.Globalization—Includes classes that specify culture-related information including the language, country/region, calendars, format patterns for dates, currency, and numbers, system, T0—Includes types that support synchronous and asynchronous reading from and writing to data streams and files. System. Ling Includes classes that allow you to use Language Integrated Queries in your applications. system.Messaging—Provides classes that help you to control the transmission of message queues on the network. System.Net —Provides a simple programming interface to many of the protocols used on the Internet. System Net.Sockets—Includes classes that support the Windows Sockets interface. If you have Worked with the Winsock API, you should be able to develop applications using the Socket class. System.Reflection—Includes classes and interfaces that return information about fyPes, methods, and fields. The System. Reflection namespace alsohas the ability to dynamically create and invoke types. System. Runtime Remoting—Provides classes and interfaces that allow developers to create and configure distributed applications. System. Security —Includes classes that support the structure of the Common Language Runtime (cr) Security system. System Runtine,Serialization— Contains classes that allow you to serialize and deserialize the objecis. Serialization is the process of converting an object into a linear sequence of bytes. Deserialization is the process of recreating objects from the sequence of bytes. System. Threading—Includes classes and interfaces that enable multithreaded programming, System, Web—Includes classes and interfaces that allows you to create browser/server communication ased applications. System.Web. Security—Includes classes that are used to implement ASP.NET security in Web server applications. 403 en eee
You might also like
Introduction To
PDF
100% (4)
Introduction To
90 pages
Chapter One: Ju, Jit, Faculty of Computing and Informatics
PDF
100% (1)
Chapter One: Ju, Jit, Faculty of Computing and Informatics
44 pages
C# Introduction: by Prof. Vasanti Dutta
PDF
No ratings yet
C# Introduction: by Prof. Vasanti Dutta
23 pages
Chapter 1
PDF
No ratings yet
Chapter 1
67 pages
Variables, Data Types and Operators
PDF
No ratings yet
Variables, Data Types and Operators
6 pages
Chapter 3 Programming Fundamentals in C#
PDF
No ratings yet
Chapter 3 Programming Fundamentals in C#
78 pages
C# Notes
PDF
No ratings yet
C# Notes
488 pages
CS Fundamentals v2
PDF
No ratings yet
CS Fundamentals v2
97 pages
Edx C# Course
PDF
No ratings yet
Edx C# Course
32 pages
C# Slide Teacher
PDF
No ratings yet
C# Slide Teacher
166 pages
Simple C Tutorial
PDF
No ratings yet
Simple C Tutorial
52 pages
Unit1 Part2
PDF
No ratings yet
Unit1 Part2
56 pages
C Sharp Programming
PDF
100% (3)
C Sharp Programming
76 pages
Unit 2
PDF
No ratings yet
Unit 2
59 pages
Introducing C
PDF
No ratings yet
Introducing C
6 pages
C# Book New
PDF
No ratings yet
C# Book New
30 pages
VisualStudio.net
PDF
No ratings yet
VisualStudio.net
22 pages
Unit 2
PDF
No ratings yet
Unit 2
64 pages
Session 2 CSharp Basics
PDF
No ratings yet
Session 2 CSharp Basics
105 pages
Csharp Programming
PDF
No ratings yet
Csharp Programming
57 pages
Unit1 Part2
PDF
No ratings yet
Unit1 Part2
51 pages
Unit 2 - Language Basics
PDF
No ratings yet
Unit 2 - Language Basics
40 pages
3.1. C# Programming
PDF
No ratings yet
3.1. C# Programming
41 pages
EContent 11 2022 04 15 10 25 44 Unit 1pptx 2022 03 07 13 47 27
PDF
0% (1)
EContent 11 2022 04 15 10 25 44 Unit 1pptx 2022 03 07 13 47 27
17 pages
Unit 2 Notes11
PDF
No ratings yet
Unit 2 Notes11
31 pages
ADT-II - Unit 2
PDF
No ratings yet
ADT-II - Unit 2
62 pages
Chapter 2 Materials
PDF
No ratings yet
Chapter 2 Materials
66 pages
Points To Be Discussed
PDF
100% (1)
Points To Be Discussed
35 pages
C Sharp Programming
PDF
No ratings yet
C Sharp Programming
67 pages
C++ Project
PDF
No ratings yet
C++ Project
42 pages
Implementing OOP in C#
PDF
No ratings yet
Implementing OOP in C#
53 pages
Patric Boscolo Microsoft Academic Program
PDF
No ratings yet
Patric Boscolo Microsoft Academic Program
56 pages
Intro To C#
PDF
No ratings yet
Intro To C#
90 pages
Csharp
PDF
100% (5)
Csharp
12 pages
New Features in CSharp 4.0
PDF
No ratings yet
New Features in CSharp 4.0
13 pages
Introducing C# Programming: Compiled by Mezgebu A
PDF
No ratings yet
Introducing C# Programming: Compiled by Mezgebu A
60 pages
Dot Net Notes
PDF
No ratings yet
Dot Net Notes
30 pages
C# Tutorial
PDF
No ratings yet
C# Tutorial
10 pages
New Features in CSharp 4.0
PDF
No ratings yet
New Features in CSharp 4.0
13 pages
C# Lecture
PDF
No ratings yet
C# Lecture
6 pages
C# Notes
PDF
No ratings yet
C# Notes
50 pages
C# Language Reference
PDF
No ratings yet
C# Language Reference
218 pages
Module 1-1
PDF
No ratings yet
Module 1-1
20 pages
Introduction To C#
PDF
No ratings yet
Introduction To C#
24 pages
C# Jumpstart Module 1 Intro
PDF
No ratings yet
C# Jumpstart Module 1 Intro
31 pages
Csharp
PDF
No ratings yet
Csharp
96 pages
Introduction To C Sharp
PDF
No ratings yet
Introduction To C Sharp
72 pages
(C#) Chapter - 4
PDF
No ratings yet
(C#) Chapter - 4
58 pages
C#
PDF
No ratings yet
C#
9 pages
Unit 2
PDF
No ratings yet
Unit 2
34 pages
Dot Net Complete Note - Unlocked
PDF
No ratings yet
Dot Net Complete Note - Unlocked
155 pages
C# Introduction
PDF
100% (1)
C# Introduction
65 pages
C# Unit - II
PDF
No ratings yet
C# Unit - II
90 pages
Chapter 5
PDF
No ratings yet
Chapter 5
38 pages
Chap 12 13
PDF
No ratings yet
Chap 12 13
80 pages
Backgroundimagelayout: The Monthcalendar Control
PDF
No ratings yet
Backgroundimagelayout: The Monthcalendar Control
7 pages
Module 5
PDF
No ratings yet
Module 5
15 pages
ML 0001
PDF
No ratings yet
ML 0001
17 pages
Chap 5 Part 1
PDF
No ratings yet
Chap 5 Part 1
25 pages
Module 4
PDF
No ratings yet
Module 4
18 pages
IOT
PDF
No ratings yet
IOT
5 pages