1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional C# Third Edition phần 10 pot

137 282 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 137
Dung lượng 2,46 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

For example, to declare aninteger int variable called myInt, we would use the following code: int 7x; //invalid, number cannot start identifierint x7; //valid, number may be part of iden

Trang 1

The for Loop

Now let’s discuss the forloop, introduced in the previous code snippet What we have here is the C#equivalent of this Visual Basic code:

Dim I As Integer

For I = 1 To 3

listBox1.Items.Add “Details of the Employee”

Next

The idea of the Forloop in Visual Basic is that you start off by initializing a variable, called the loop

con-trol variable, and each time you go round the loop, you add something to the loop concon-trol variable until it

exceeds a final value This is quite useful, but gives you almost no flexibility in how the loop works.Although you can change the value of the increment, or even make the increment negative, by using theStepfacility, the loop always works by counting, and the test of whether the loop exits is alwayswhether the variable has reached a preset minimum or maximum value

In C# the forloop generalizes this concept The basic idea of the forloop in C# is this: At the beginning

of the loop you do something, at each step of the loop you do something else in order to move to thenext iteration, and in order to determine when to exit from the loop, you perform some test The follow-ing table provides a comparison between the Visual Basic and C# versions of this loop

At start of loop Initialize the loop control variable Do something

To test whether to exit loop Check whether the loop control Test some condition

variable has reached a certain value

At end of each iteration Increment the loop control variable Do something

This might look a bit vague, but it does give you a lot of flexibility! For example, in C#, instead of adding aquantity to the loop control variable at each iteration, you might multiply its value by some number Orinstead of adding on a fixed amount you might add some number that you’ve read in from a file and whichchanges with each iteration The test doesn’t have to be a test of the value of the loop control variable Itcould be a test of whether you have reached the end of the file What this adds up to is that, by a suitablechoice of the start action, test, and action at the end of each iteration, the for loop can effectively perform thesame task as any of the other loops in Visual Basic (For, For Each, Do, and While) Alternatively the loopcan work in some manner for which there is no simple equivalent in Visual Basic The C# forloop reallygives you complete freedom to control the loop in whatever manner is appropriate for the task at hand

We should point out, however, that C# also does support foreach , do , and while loops.

Now let’s look at the syntax The C# version of the previous forloop looks like this:

for (int I=0 ; I<3 ; I++) {

this.listBox1.Items.Add(Employees[I].Name);

this.listBox1.Items.Add(Employees[I].ToString());

this.listBox1.Items.Add(“”);

} Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 2

As you can see, the forstatement itself takes three different items inside its parentheses These items areseparated by semicolons:

❑ The first item is the action that is performed right at the start of the loop in order to initialize theloop In this case we declare and initialize the loop control variable

❑ The next item is the condition that will be evaluated to determine whether the loop should exit

In this case our condition is that Imust be less than 3 The loop continues as long as this tion is trueand exits as soon as the condition evaluates to false The condition will be evalu-ated at the beginning of each iteration, so that if it turns out to be falseright at the start, thestatement inside the loop does not get executed at all

condi-❑ In the third item is the statement that is executed at the end of each iteration of the loop VisualBasic loops always work by incrementing some number

Even though the syntax looks unfamiliar, once you’ve familiarized yourself with it, you can use the forloop in very powerful ways For example, if you want to display all the integer powers of 2 that are lessthan 4000 in a list box, you can write this:

for (int I = 2 ; I<4000 ; I*=2) listBox1.Items.Add(I.ToString());

You can achieve the same result in Visual Basic, but it wouldn’t be as easy; for this particular example,you might want to opt for a whileloop in Visual Basic

Although the types available in C# are slightly different from Visual Basic types, most of the types thatyou are familiar with in Visual Basic do have equivalents in C# For example, the Visual Basic Doubletype translates to doublein C#; The C# equivalent of the Datetype is the.NET base class, DateTime,which implements a huge number of methods and properties to allow you to extract or set the dateusing different formats

One exception, however, is Variant, for which there is no equivalent in C# The Varianttype is a verygeneric type, which to some extent exists only in order to support scripting languages that are not aware

of any other data types The philosophy of C#, however, is that the language is strongly typed The idea isthat if, at each point in the program, you have to indicate the data type you are referring to, at least one

1221

C# for Visual Basic 6 Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 3

major source of runtime bugs is eliminated Because of this, a Varianttype isn’t really appropriate to C#.However, there are still some situations in which you do need to refer to a variable without indicatingwhat type that variable is, and for those cases C# does have the objecttype C#’s objectis analogous toObjectin Visual Basic However, Objectspecifically refers to a COM object, and therefore can only beused to refer to objects, which in Visual Basic terms means to reference data types For example, you can-not use an objectreference to refer to an Integeror to a Singletype In C#, by contrast, an object0method can be used to refer to any NET data type, and since all data types are NET data types, thismeans that you can legitimately convert anything to an object, including int, float, and all the prede-fined data types To this extent, objectin C# does perform a similar role to Variantin Visual Basic.

Value and reference types

In Visual Basic there is a sharp distinction between value types and reference types Value types includemost of the predefined data types: Integer, Single, Double, and even Variant(though strictly speak-ing Variantcan also contain a reference) Reference types are any object, including class modules thatyou define and ActiveX objects As you will have noticed through the samples in this appendix, C# alsomakes the distinction between value and reference types However, C# is more flexibility to the extentthat it permits you, when defining a class, to specify that that class should be a value type You do this

by declaring the class as something called a struct As far as C# is concerned, a struct is basically a special

type of class that is represented as a value rather than a reference The overhead involved in ing structs and destroying them when we are finished with them is less than that involved when instan-tiating and destroying classes However, C# does restrict the features supported by structs In particular,you cannot derive classes or other structs from structs The reasoning here is that structs are intended to

instantiat-be used for really lightweight, simple objects, for which inheritance isn’t really appropriate In fact, allthe predefined classes in C#, such as int, long, float, and doubleare actually NET structs, which iswhy we can call methods such as ToString()against them The data type string, however, is a refer-ence type and so is really just a class

Operators

We need to say a couple of words about operators in C#, because they do differ somewhat from VisualBasic operators, and this can catch you off guard if you are used to the Visual Basic way of working InVisual Basic there are really two types of operator:

❑ The assignment operator, =, which assigns values to variables

❑ All the other operators, such as +, -,*, and /, which each return some value

There is an important distinction here in that none of the operators, apart from =, has any effect in terms

of modifying any value On the other hand, = assigns a value but does not return anything There are nooperators that do both

In C#, this categorization simply does not exist The rule in C# is that all operators return a value, and

some operators also assign some value to a variable We have already seen an example of this when weexamined the addition assignment operator, +=:

int A=5, B=15;

A+=B; // performs an arithmetic operation AND assigns result (20) to A

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 4

+= returns a value as well as assigning the value It returns the new value that has been assigned.Because of this we could actually write:

int A=5, B=15;

int C = (A+=B);

This will have the results that both Aand Cwill be assigned the value 20 The assignment operator, =,also returns a value It returns the value that has been assigned to the variable on the left side of theexpression This means that you can write code like this:

simulta-// assume X and Y are some other variables that have been initialized

bool B;

if ( B = (X==Y) ) DoSomething();

This code looks daunting at first sight, but it is quite logical Let’s break it down The first thing the puter will do is check the condition X==Y Depending on whether Xand Ycontain the same data, thiswill either return trueor falseand this value will be assigned to the variable B However, since theassignment operator also returns the value that has just been assigned to it, the complete expression B =(X==Y)will also return this same value (trueor false) This return value will then be used by the ifclause to determine whether to execute the conditional DoSomething()statement The result of thiscode is that the condition X==Yis tested to determine whether the conditional statements should be exe-cuted, and at the same time we have stored the results of this test in the variable B

com-The ternary operator

We do not have space in this appendix to go over all the various operators that are available in C# They

are detailed in Chapter 2 of this book However, we will mention the ternary operator (also known as the

conditional operator) because it has a very unusual syntax The ternary operator is formed from the twosymbols ?and : It takes three parameters and is actually equivalent to an IIfstatement in Visual Basic

It is used syntactically like this:

// B, X and Y are some variables or expressions B is a Boolean

B ? X : Y

The way it works is that the first expression (the one before the ?symbol) is evaluated If it evaluates totrue, then the result of the second expression is returned, but if it evaluates to falsethen the result of

1223

C# for Visual Basic 6 Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 5

the third expression is returned instead This provides an extremely compact syntax for conditionallysetting the value of variable For example, we can write:

string animal = (legs==8) ? “octopus” : “dog”;

which yields the same result as:

With the Visual Basic Iiffunction, this can be achieved with:

strAnimal = IIf(intLegs = 8, “octopus”, “dog”)

Summar y

In this appendix, we have presented a brief introduction to C# through the eyes of a Visual basic mer We have found quite a few differences in syntax In general, C# syntax allows most statements to beexpressed in a more compact way We have also found many similarities between the languages; for exam-ple in their use of classes (or class modules in VB), value and reference types, and many of the syntacticalstructures However, we have also seen how C# supports many powerful features, particularly thoserelated to inheritance and classic object-oriented programming that are not available in Visual Basic

program-Appendix A of this book contains an introduction to object-oriented programming, which is key to anyserious C# development effort

Making the transfer from Visual Basic to C# does require a fair bit of learning, but is well worth it,because the methodology of C# allows you to code not only any application that you could have devel-oped in Visual Basic, but also a wide range of other applications that would be too difficult, if not impos-sible, to design in a good, well-structured, and maintainable manner in Visual Basic With C# you alsoget the added bonus of the NET runtime and all its associated benefits

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 6

C# for Java Developer s

At first glance, Java developers might not get particularly excited about C# code, because of thesyntactical similarity between it and Java However, look more closely and you will see subtle yetsignificant differences: features such as operator overloading, indexers, delegates, properties, andtype safe enumerations in C#

This appendix focuses on applying much-loved Java programming tricks to C# code, highlightingfeatures that C# adds to the picture, and pointing out tricks that C# cannot do (although you won’tfind many of those) Of course, we assume that as a reader of this appendix, you are a professionalJava developer; so we will not go into too much detail when describing the Java language

Star ting OutLet’s take a look at the infamous “Hello World!” example in Java:

public class Hello {public static void main(String args []) {System.out.println(“Hello world! This is Java Code!”);

}}

The corresponding C# code for this is as follows:

Trang 7

The first thing that you’ll notice is that the two appear to be very similar syntactically and both guages are case-sensitive C# is object-oriented like Java, and all functionality must be placed inside aclass (declared by the keyword class) These classes can contain methods, constructors, and fields just

lan-as Java cllan-asses can, and a C# cllan-ass can inherit methods and fields from another cllan-ass or interface lan-as inJava The implementation of classes and methods is similar in both languages

C# code blocks are enclosed by braces just as in Java The entry point to a C# application is the staticMain()method, as required by the compiler (similar to Java but note the uppercase “M”) Also note thatonly one class in the application can have a Main()method Similar to Java, the static keyword allowsfor the method to be called without creating an instance of the class first For the Main()method in C#you have the choice of either a voidor int return type voidspecifies that the method does not return avalue and intspecifies that it returns an integer type

The usingkeyword in C# corresponds to the import keyword in Java Therefore, in the C# code above,

we are essentially importing the C# equivalent of a class package called System In C#, a class package is

called a namespace, and we will look more closely at these in the next section.

Note that although we have written it with a lowercase s here, in C# the string type can also be written with a capital S as String You will also notice that the array rank specifier ([]) has been shifted from infront of the argsvariable in the Java example, to between the string type and argsvariable in the C#sample In fact, this specifier can occur before or after the variable in Java However, in C#, the arrayrank specifier must appear before the variable name because an array is actually a type of its own indi-cated by type [] We’ll discuss arrays in more depth a bit later

Finally, as you might expect, the names of methods tend to differ between the languages For example,

in Java we would use System.out.println()to display text in the command console The equivalent

to this method in C# is System.Console.WriteLine()

Compiling and Running C# Code

In Chapter 2, we noted that like Java code, C# source code is compiled in two stages: first to

Intermediate Language (IL), and then to native code To run the previous C# code, you need to save itwith an appropriate filename (for example, HelloWorld) and file extension cs, and then compile it to ILusing the csc command:

Trang 8

within that file automatically becomes a part of the specified package Also, a Java package name is ciated with the folder containing the class file in that they must have the same name The com.samplespackage must therefore be in class files that exist in the com/samples folder Let’s take a look at someexamples of how packages work in Java:

asso-package java2csharp.javasamples;

public class Hello {public static void main(String args []) {System.out.println(“Hello world! This is Java Code!”);

}}

The following list provides examples of how the previous code could be referenced or executed This listassumes that the class file has been made available to the JRE:

❑ From the command line:

java java2csharp.javasamples.Hello

❑ As a direct reference in the code:

public class Referencer {java2csharp.javasamples.Hello myHello = new java2csharp.samples.Hello();

❑ By utilizing the importdirective one could omit fully qualified package names, so Referencercould also be written as:

As you can see, we delimit layers of namespaces using the operator, as in Java Note that C# does notrequire an asterisk (*) needed in C#—applying the usingdirective implicitly imports all elements of thespecified namespace You will also have noticed the major difference from Java here: the use of name-space parentheses in which we place classes associated with the namespace The advantage of using theparentheses like this is that we then disassociate package names from directory structures: feasibly we

1227

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 9

could place a file containing this namespace anywhere within the directory as long as the CLR nizes it Therefore, it also enables us to call the file containing these classes anything we wish (it doesn’thave to be the same name as the class as in Java); we can have more than one public class defined perfile; and we can split the classes defined in this namespace into different files in different parts of thedirectory structure, as long as the namespace declaration appears in each of the files.

recog-We can also introduce multiple namespaces in the same file with no restriction recog-We could, for example,add the definition of a new class and place it in a new namespace in the same file and still not be outsidethe bounds of the language:

Namespaces may also be defined within other namespaces This type of flexibility is impossible in Javawithout having to create a subdirectory We could change the previous example so that the AnotherHelloclass is in the java2csharp.csharpsamples.hellosamplesnamespace:

public static void Main(string [] args)

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 10

{System.Console.WriteLine(“Hello again! This is more C# code!”);

}}}}

Java classes are part of a package; all classes created are part of the default package C# mimics this tionality Even if you do not declare one, a default namespace is created for you It is present in every fileand available for use in named namespaces Just as in Java you cannot change package information, inC# namespaces cannot be modified either Packages can span multiple files in the same folder; name-spaces can span multiple files in any number of folders, and even multiple assemblies (the name given

func-to code libraries in NET), as discussed in Chapter 13

Note that the default accessibility for types inside a namespace is internal You must specify types aspublicif you want them available without full qualification; however, we strongly advise against thispractice No other access modifiers are allowed In Java, internal package types may also be marked asfinalor abstractor not marked at all (this default access makes them available only to consumersinside the package) Access modifiers are discussed later in this appendix

One final feature of namespaces not available to Java packages is that they may be given a usingalias.using aliases make it very easy to qualify an identifier to a namespace or class The syntax is simple.Suppose you had a namespace Very.Very.Long.NameSpace.Name You could define and use a usingalias (here VVLNN) for the namespace as follows:

using VVLNN = Very.Very.Long.Namespace.Name;

Declaring VariablesC# follows a similar scheme of variable declaration to Java, where the declaration consists of a datatypekeyword and followed by the name of the variable to hold that datatype For example, to declare aninteger (int) variable called myInt, we would use the following code:

int 7x; //invalid, number cannot start identifierint x7; //valid, number may be part of identifierint x; //valid

int x$; //invalid, no symbols allowedint @class; //valid, prefix @ allows it to be used as an identifierint @7k; //invalid, prefix @ only works for keywords

1229

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 11

Variable Naming Conventions

Java uses camel-case notation for methods, properties, and variables, meaning that they are lowercasefor the first letter in the name and capital letter for the first letter of every other word in the name Thefirst letter of class and object names in Java are uppercase The following snippet shows the general syn-tax most Java programmers use:

int id;

int idName;

int id_name; //practiced also

final int CONSTANT_NAME; //widely adopted

int reallyLongId;

public class ClassName //every first letter capitalized

public interface InterfaceName

public void method(){}

public void myMethodName(){}

Based on the C# library classes, it is safe to make certain assumptions about C# naming conventions Adocumented naming guideline for C# was not provided at the time of this writing Each first letter ofall method and property identifier names is capitalized, as is each first letter of all class and namespacenames Interfaces are preceded with an I Variables are camel-cased, as shown in the following examples:

int id;

int idName;

public class ClassName //every first letter capitalized

public interface IInterfaceName //interface name preceded by I

public void Method(){} // first letter always capitalized

public void MyMethodName(){} // first letter of all other words capitalized

Data Types

Types in Java and C# can be grouped into two main categories: value types and reference types As you

are probably aware, value type variables store their data on the stack, while reference types store data onthe heap Let’s start by considering value types

Value Types

There is only one category of value type in Java; all value types are by default the primitive data types

of the language C# offers a more robust assortment Value types can be broken down into three maincategories:

❑ Simple types

❑ Enumeration types

❑ Structures

Let’s take a look at each of these in turn

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 12

Simple types

The C# compiler recognizes a number of the usual predefined datatypes (defined in the System BaseClass namespace), including integer, character, Boolean, and floating point types Of course, the valueranges of the indicated types may be different from one language to another Below we discuss the C#types and their Java counterparts

Integer values

C# has eight predefined signed and unsigned integer types (as opposed to just four signed integer types

in Java):

C# Type Description Equivalent in Java

When an integer has no suffix the type to which its value can be bound is evaluated in the order int,uint, long, ulong, decimal Integer values may be represented as decimal or hexadecimal literals Inthe following example the result is 52 for both values:

assign-Boolean values

The booltype, as in Java, is used to represent the values trueand falsedirectly, or as the result of anequation as shown below:

bool first_time = true;

bool second_time = (counter < 0);

1231

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 13

Decimal values

C# introduces the decimal type, which is a 128-bit data type that represents values ranging from mately 1.0x10-28 to 7.9x1028 They are primarily intended for financial and monetary calculations whereprecision is important (for example, in foreign exchange calculations) When assigning the decimal type avalue, mmust be appended to the literal value Otherwise, the compiler treats the value as a double.Because a double cannot be implicitly converted to a decimal, omitting the m requires an explicit cast:

approxi-decimal precise = 1.234m;

decimal precise = (decimal)1.234;

Floating-point values

The following table lists the C# floating type values and their Java equivalents

C# Type Description Equivalent in Java

Float Signed 32-bit floating point float

double Signed 64-bit floating point double

Floating-point values can either be doubles or floats A real numeric literal on the right-hand side of anassignment operator is treated as a double by default Because there is no implicit conversion from float

to double you may be taken aback when a compiler error occurs The following example illustrates thisproblem:

float f = 5.6;

Console.WriteLine(f);

This example produces the following compiler error message

Literal of type double cannot be implicitly converted to type ‘float’; use an ‘F’suffix to create a literal of this type

There are two ways to solve this problem We could cast our literal to float, but the compiler itselfoffers a more reasonable alternative Using the suffix Ftells the compiler this is a literal of type floatand not double:

float f = 5.6F;

Although it is not necessary, you can use a D suffix to signify a doubletype literal

Enumeration types

An enumeration is a distinct type consisting of a set of named constants In Java you can achieve this by

using staticfinal variables In this sense, the enumerations may actually be part of the class that isusing them Another alternative is to define the enumeration as an interface The following exampleillustrates this concept:

interface Color {

static int RED = 0;

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 14

static int GREEN = 1;

static int BLUE = 2;

}

Of course, the problem with this approach is that it is not type-safe Any integer read in or calculated can

be used as a color It is possible, however, to programmatically implement a type-safe enumeration inJava by utilizing a variation of the Singleton pattern, which limits the class to a predefined number ofinstances The following Java code illustrates how this can be done:

final class Day { // final so it cannot be sub-classedprivate String internal;

private Day(String Day) {internal = Day;} // private constructorpublic static final Day MONDAY = new Day(“MONDAY”);

public static final Day TUESDAY = new Day(“TUESDAY”);

public static final Day WEDNESDAY = new Day(“WEDNESDAY”);

public static final Day THURDAY = new Day(“THURSDAY”);

public static final Day FRIDAY = new Day(“FRIDAY”);

}

As you can see from the above example, the enumerated constants are not tied to primitive types, but toobject references Also, because the class is defined as final, it can’t be sub-classed, so no other classescan be created from it The constructor is marked as private, so other methods can’t use the class to cre-ate new objects The only objects that will ever be created with this class are the static objects the classcreates for itself the first time the class is referenced

Although the concept is pretty simple, the workaround involves techniques that may not be ately apparent to a novice after all, we just want a readily available list of constants C#, in contrast, pro-vides inbuilt enumeration support, which also ensures type safety To declare an enumeration in C# theenumkeyword is used In its simple form an enummight look like this:

immedi-public enum Status{

Working,Complete,BeforeBegin}

In this example, the first value is 0 and the enumcounts upward from there, Completebeing 1 and so

on If for some reason you are interested in having enumrepresent different values you can do so byassigning them as follows:

public enum Status{

Working = 131,Complete = 129,BeforeBegin = 132}

1233

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 15

You also have the choice of using a different numerical integral type by inheriting from long, short, orbyte intis always the default type, as demonstrated in this snippet:

public enum Status : int

sizeof()operator to identify the differences between the different versions of Status:

One of the major differences between a C# structure (identified with the keyword struct) and an object

is that, by default, the struct is passed by value, while an object is passed by reference There is no logue in Java to structures Structures have constructors and, methods; they can have other membersnormally associated with a C# class too: indexers (for more on these members see Chapter 4), properties,operators, and even nested types Structures can even implement interfaces By using structs we can cre-ate types that behave in the same way as, and share similar benefits to, the built-in types The followingsnippet demonstrates how a structure can be used:

ana-public struct EmployeeInfo

{

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 16

public string firstNamepublic string lastNamepublic string jobTitlepublic string deptpublic long employeeID}

Although we could have created a class to hold the same information, using a struct is a little more cient here because it is easier to create and copy it The following snippet shows how to copy valuesfrom one struct to another:

❑ A struct cannot inherit from another struct or from classes

❑ A struct cannot act as the base for a class

Although a struct may declare constructors, those constructors must take at least one argument.

❑ The struct members cannot have initializers

Structs and attributes

Attributes (or compiler directives, discussed in Chapter 10 and Appendix D) can be used with structures

to add more power and flexibility to them The StructLayoutattribute in the System.Runtime.InteropServicesnamespace, for example, can be used to define the layout of fields in the struct It ispossible to use this feature to create a structure similar in functionality to a C/C++ union A union is adata type whose members share the same memory block It can be used to store values of different types

in the same memory block In the event that one does not know what type the values to be received will

be, a union is a great way to go Of course there is no actual conversion happening; in fact there are nounderlying checks on the validity of the data The same bit pattern is simply interpreted in a differentway The following snippet demonstrates how a union could be created using a struct:

[StructLayout(LayoutKind.Explicit)]

public struct Variant{

[FieldOffset(0)]public int intVal;

[FieldOffset(0)]public string strinVal;

[FieldOffset(0)]public decimal decVal;

[FieldOffset(0)]public float floatVal;

[FieldOffset(0)]public char charVal;

}

1235

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 17

The FieldOffsetattribute applied to the fields is used to set the physical location of the specified field.Setting the starting point of each field to 0ensures that any data store in one field will overwrite to a cer-tain extent whatever data may have been stored there It follows then that the total size of the fields will

be the size of the largest field, in this case the decimal

Reference Types

All a reference type variable stores is the reference to data that exists on the heap Only the memoryaddresses of the stored objects are kept in the stack The object type, arrays, and interfaces are all refer-ence types Objects, classes, and the relationship between the two do not differ much between Java andC# You will also find that interfaces, and how they are used, are not very different in the two languages

We will look at classes and class inheritance in C# in more depth later in this document Strings can also

be used the same way in either C# or Java C# also introduces a new type of reference type called a

dele-gate Delegates represent a type-safe version of C++ function pointers (references to methods) and are

discussed in Chapter 6

Arrays and collections

Array syntax in C# is very similar to that used in Java However, C# supports “jagged” arrays, and addsmultidimensional arrays (as opposed to the arrays of arrays supported by Java):

int[] x = new int[20]; //same as in Java except [] must be next to type

int[,] y = new int[12,3]; //same as int y[][] = new int[12][3];

int[][] z = new int[5][]; //same as int x[][] = new int[5][];

In C#, arrays are actual types, so they must be written syntactically as such Unlike in Java, you cannotplace the array rank specifier []before or after the variable; it must come before the variable and afterthe data type Since arrays are types, they have their own methods and properties For example, we canget the length of array xusing:

int xLength = x.Length;

We can also sort the array using the static Sort()method:

Array.Sort(x);

You should also note that although C# allows us to declare arrays without initializing them, we cannotleave the determination of the size of an array until runtime If you need a dynamically sized array, youmust use a System.Collections.ArrayListobject (similar to the Java’s Arraylistcollection) Wecover C# collection objects in depth in Chapter 9

Type Conversion and Casting

Type conversion in Java consists of implicit or explicit narrow and wide casting, using the ()operator asneeded It is generally possible to perform similar type conversions in C# C# also introduces a number

of powerful features built into the language These include boxing and unboxing.

Because value types are nothing more than memory blocks of a certain size, they are great to use forspeed reasons Sometimes, however, the convenience of objects is good to have for a value type Boxingand unboxing provide a mechanism that forms a binding link between value types and reference types

by allowing them to be converted to and from the object type

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 18

Boxing an object means implicitly converting any value type to type Object An instance of Objectiscreated and allocated, and the value in the value type is copied to the new object Here is an example ofhow boxing works in C#:

int x = 10;

Object obj = x;

int y = (int) obj;

Another powerful feature of C# dealing with casting is the ability to define custom conversion operatorsfor our classes and structs We deal with this issue in depth in Chapter 5

OperatorsThe following table lists the C# operators

Conditional (the Ternary Operator) ?:

Overflow exception control checked uncheckedIndirection and Address * -> &(unsafe code only) []

1237

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 19

Java developers will immediately spot that C# operators are very similar to Java’s However, there are afew significant differences.

To determine whether an object belongs to a given class or any of the parent classes Java uses theinstanceofoperator The C# equivalent of instanceofis the isoperator It returns trueif the run-time type of the given class is compatible with the specified type Here’s an example of its use:

string y = “a string”;

sizeof(<ValueType>), where <Value Type>is the struct or enum Note that sizeofmay only beused in an unsafe context The sizeofoperator cannot be overloaded

The typeofoperator is used to get an instance of a type’s System.Typeobject without having to create

an instance of the type In Java, every type has a public static class variable that returns a handle to theClassobject associated with that class The typeofoperator provides this type of functionality Just as

we saw with sizeof, the syntax is very simple The statement typeof(<Type>)where <Type>is anyuser-defined type will return you the type object of that type

Flow Control and Iteration

Most of the flow control statements are conceptually and syntactically very similar to Java’s Here’s abrief summary:

Trang 20

switch(option){

case 1:

//do somethingbreak;

for

for (int i = 0; i <10; i++){

// iterates 10 times}

while

bool condition = false;

while (!condition){

// do something that may alter the value of the condition Boolean}

do while

bool condition;

do{// do something that may alter the value of the condition Boolean// at least one iteration occurs whatever the initial value of condition} while (condition);

foreach

C# introduces a foreachstatement, used specifically to iterate through, and not change collection orarray entries to get the desired information Changing the contents might have unpredictable sideeffects The foreachstatement usually takes the following form:

foreach (ItemType item in TargetCollection)

1239

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 21

ItemTyperepresents the data type stored in the collection or array and TargetCollectionrepresentsthe actual array or collection There are two sets of requirements that a collection you want to iteratethrough using the foreachstatement must meet The first set has to do with the composition of the col-lection itself They are as follows:

❑ The collection type must be an interface, class, or struct

❑ The collection type must include a GetEnumerator()method for returning an enumeratortype An enumerator type is basically an object that allows you to step through a collection item

by item

The second set of requirements deal with the composition of the enumerator type returned by theGetEnumerator()method mentioned above Here is the list of requirements:

❑ The enumerator should provide a Boolean method MoveNext()

❑ MoveNext()should return true if there are more items in the collection

❑ MoveNext()should step to the next item in the collection at each invocation

❑ The enumerator type must provide a property named Currentthat returns an ItemType(or atype that can be converted to ItemType)

❑ The property accessor Currentshould return the current element of the collection

The following snippet of C# code uses foreachto iterate through a Hashtablecollection:

Hashtable t = new Hashtable();

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 22

Access Modifiers

As with Java, we can add the usual modifiers to the start of the class or member declaration to modifythe behavior of the class or member The following table list the C# modifiers and their Java equivalents

Access Modifier Java Equivalent Description

public public No restrictions on access Members of enum and

interface, as well as namespaces, are public bydefault

private private Accessible only to the declaring class Members

of class and struct are private by default

internal n/a Accessible to files in the same assembly

protected n/a Accessible to the declaring class, and any

sub-class of the declaring sub-class In C# protectedismore restrictive than in Java Protected accesswill not allow other files in the same assembly

to access the member

protected internal protected Accessible to assembly files and subclasses of

declaring class

The private keyword is used to make methods and variables accessible only from within the containingclass It serves the same function in both languages The publicmodifier allows entities outside thepackage/namespace to access the members of the class However, C# and Java differ in the way pro-tected and default are handled While in Java, protected makes the method or variable accessible toclasses in the same package or subclasses of the class, in C# protected makes code only visible to thatclass and subclasses that inherit from it

C# also introduces a new access modifier: internal The internalkeyword modifies data members sothat they are visible to all code within the entire component but not clients of that component The dif-ference between the nomodifier in Java (which signifies an element that is accessible only to elementswithin the package) and internalis that internalis accessible to all elements of the assembly, whichcan span multiple namespaces

Class Members

As we have seen throughout this document, the differences in syntax between C# and Java when ing and referring to classes and their members is minimal However, there are marked differences inclass member modifier syntax, as explained in the following table

declar-1241

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 23

Member Modifiers Java Equivalent Description

virtual n/a Allows target members to be overridden by an

inher-ited class (the default in Java)

static static Target member marked as staticbelongs to class

and not instance of class Hence, there is no need toinstantiate the class in order to gain access to it

event n/a Used to bind client code to events of the class, the

event modifier allows you to specify a delegate thatwill be called when some event in your code occurs.Note that it is the job of the class programmer todefine when and where the event is raised, and thejob of the subscriber to choose how to handle it

abstract abstract Indicates that the target member is implicitly virtual

and has no implementation code The derived classmust provide this implementation and the imple-mented method must be marked as override

const final Indicates that the target member cannot be modified

Java also has a constkeyword, which at the time ofthis writing is simply a reserved word

readonly n/a Indicates that the target member can only be assigned

values in its declaration or in the constructor of itscontaining class

extern n/a Indicates that the target member is implemented

externally This modifier is typically used with theDllImportattribute

override n/a Indicates that the target member provides a new

imple-mentation of a member inherited from a base class

For more information on delegates and events, refer to Chapter 6

As with Java, defining abstract methods in C# mandates that the class be abstract

C# does not have a native modifier, and there is also no C# version of transient, volatile, or synchronized

at the time of writing In Java, using native indicates that the method is implemented in a dependent language It requires that the method be abstract since the implementation is to be foundelsewhere The closest relative to this type of functionality is the externmodifier Using externimpliesthat the code is implemented externally (by some native DLL for example) Unlike Java, however, there

platform-is no need to use the abstractkeyword in association with it In the following snippet, the Flowerclassdisplays an example of how externcan be used:

public class Flower

{

public Flower(){}

public extern int GetColor();

// rest of Flower class definition

}

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 24

This doesn’t make much sense without using the DllImportattribute to specify the external tation The following code provides the appropriate modifications, assuming there is a See()functionexported by the User32.dll resource:

implemen-public class Flower{

public Flower(){}

[System.Runtime.InteropServices.DllImport (“User32.dll”)]

public static extern int GetColor();

// rest of Flower class definition}

Note that we have now marked GetColor()as static The DllImportattribute requires this of themethods it is used on

Passing as reference to methods

Java and C# differ extensively in syntax and ideology regarding the way methods are handled by anobject For one thing, in C# not all reference data type parameters are passed as references and not allsimple data types have to be passed by value You have the option to pass arguments by value as an inparameter (this is the default way parameters are passed) by reference as a refparameter, or as an outparameter This is illustrated by the following code:

public static void Main(string[] args){

a++;

}

This produces the following output in both C# and Java:

1010

Because ais passed by value, the value that is passed is not tied to the value a in Main() Consequently,incrementing ain the Add()method does not affect ain Main() This is probably not the behavior wewant; we would like the changes made to ato be remembered after the method call We can do this bypassing by reference instead of by value, like this:

public static void Main(string[] args){

int a = 10;

Console.WriteLine(a);

AddOne(ref a);

1243

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 25

public static void Main(string[] args)

Unlike Java, C# does not use getand setmethods to access an object’s internal attributes Instead it

combines these methods together into another kind of class member called a property A property

con-tains a getaccessor, which allows reading of internal fields of an object, and a setaccessor that allowsyou to change the value of an internal field The value keyword represents the new value to the right ofthe equals sign at assignment time Not including the appropriate accessor in the property declarationwill make the property either read-only (no set), or write-only (no get) The following class, Person,contains a few properties, called Ageand Name:

public class Person

{

private int age;

private string name;

public Person(string name)

Trang 26

age = value;

}}public string Name{

get{return name;

}}}

In the previous example, the property Agehas a getand setaccessor so you can read or write to theproperty Name, however, is created only after you create a new instance of the properties object; after thisyou can only read the value of the Nameproperty Properties are accessed as if they are publicfields:

Person john = new Person(“John Smith”);

john.Age = 21;

Console.WriteLine(“My name is {0}, and I am {1} years old.”, john.Name,john.Age);

The output of the previous code is:

My name is John Smith, and I am 21 years old

Note that property names must be unique

Destructors

C# uses destructors in a similar way to C++ They work similarly to finalizers in Java; their syntax, ever, is very different With destructors, a tilde (~) prefixes the class name:

how-~Sample(){

}

A word of advice concerning code in the destructor: the garbage collector in NET is not invoked diately after a variable goes out of scope Indeed, there are certain intervals or memory conditions thatbring the thread to life Since there is a possibility that it might be triggered in low memory situations,consider making code in the destructor as short as possible It is also a good idea to call close()onresource-intensive objects before destroying the controllers that use them

imme-Class Inheritance

Class inheritance in C# is also implemented in a very similar way to Java Both languages are based onsingle implementation inheritance (in other words a subclass is only allowed to inherit from one otherclass) and multiple interface inheritance (a class can implement as many interfaces as desired)

C# does not have Java’s extends or implements modifiers To derive from a class or implement an face in C#, we use the :operator When a class base list contains a base class and interfaces, the base

inter-1245

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 27

class comes first in the list The interfacekeyword is used to declare an interface The following codeshows examples of how to use these concepts:

//declare a parent/base class

// declare a subclass of MyBaseClass that inherits from interfaces too

class MySubClass : MyBaseClass, IFirstInterface, ISecondInterface

Preventing inheritance

In C# the sealed modifier is used to prevent accidental inheritance, because a class defined as sealed cannot be inherited from Declaring a class as final achieves the same goal Declaring a method as final alsoseals it, making it impossible to override Declaring a variable as final is essentially making it read-only;however, you can still set a final value to the value of a variable (This is different from constants, where thevalue of constants must be known at compile time so constants may only be set equal to other constants.)

Using base class members and base constructors

The keyword thisworks the same in Java and C# In Java the superreference variable is used tosignify the immediate parent class In C# the equivalent is base Take a C# class CalculateForthatprovides the ability to work out the value of integer x raised to a particular integer power (for example,

x raised to the power of three is x multiplied by x multiplied by x), given x and the power (provided anoverflow does not occur):

Trang 28

{total *= x;

}return total;

}}

We could use this class in other code like this, given a value of x of 9 and a value of power of 3:

CalculateFor myNumber = new CalculateFor(9);

int result = myNumber.ToThePower(3);

Let’s introduce a subclass of CalculateFor, ExpCalculateFor, which contains a member point variable, and the method ToTheExponent()that multiplies the result of ten to a particular power

floating-by that floating point value:

int total = 1;

for(int i = 0; i < power; i ++){

total *= base.x;

}total *= y;

return total;

}}

Notice the syntax used when referring to a base constructor in a subclass’s constructor declaration.Actually we could simplify the ToTheExponent()method to the following, reusing the functionality ofthe base class’s ToThePower()method:

public int ToTheExponent(int power){

float total = (base.x).(base.ToThePower(power));

total *= y;

return total;

}

Method overriding and hiding

In C#, method overriding is a very explicit procedure This is quite different from the Java approach,where overriding is the default behavior when the signature of a super class member is the same as thesignature of its subclass In C#, to provide method overriding functionality, the modifiers virtual andoverride are used in tandem All methods in the base class that you expect will be overridden must use

1247

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 29

the virtualkeyword To actually override them use the overridekeyword in the child class The lowing code uses an example class and subclass to demonstrate the override functionality:

Compiling and running this code produces the following output:

Generic fruit plant

Tree fruit is:->Mango

Tree fruit is:->Mango

As you can see the most derived Fruit()method is called, irrespective of our use of final cast of theMangoTreeinstance to the Plantinstance Indeed, the benefit of using method overriding is that youare guaranteed that the most derived method will always be called

Although we cannot override a method in C# unless the method was originally declared as virtual, C#

also introduces a new concept, method hiding This allows developers to redefine super-class members in

the child class and hide the base class implementation even if the base member is not declared virtual.C# uses the new modifier to accomplish this

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 30

The benefit of hiding members from the base class rather than overriding them is that you can tively determine which implementation to use By modifying the previous code we can see this concept

Running this example produces this output:

Generic plant fruitTree fruit is:->MangoGeneric plant fruit

In other words, unlike overriding, when hiding methods, the method invoked depends on the object themethod is called on For the last line of output, we cast the MangoTreeinstance back to a Plantinstancebefore calling the BearFruit()method So the Plantclass’s method is called

You should note that the new modifier can also be used to hide any other type of inherited membersfrom base class members of a similar signature

Input and OutputBeing able to collect input from the command prompt and display output in the command console is anintegral part of Java’s input/output functionality Usually in Java one would have to create an instance

of a java.io.BufferedReaderobject, using the System.infield in order to retrieve an input from thecommand prompt The following code shows a simple Java class, JavaEcho, which takes input from theconsole and echoes it back, to illustrate the use of the Java.iopackage to gather and format input andoutput:

import java.io.*;

public class JavaEcho {public static void main(String[] args)throws IOException {BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

String userInput = stdin.readLine ();

System.out.println (“You said: “ + userInput);

}}

1249

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 31

In C#, the System.Consoleclass provides methods that can provide similar functionality for readingand writing from and to the command prompt There is no need for any extra objects; the Consoleclassprovides methods that can read entire lines, read character by character, and even expose the underlyingstream being read from The members of Consoleare briefly described in the following tables.

Public Properties Description

Error Gets the system’s standard error output stream as a TextWriterobject

In Gets the system’s standard input stream as a TextReaderobject

Out Gets the system’s standard output stream as a TextWriterobject

Public Methods Description

OpenStandardError() Overloaded Returns the standard error stream as a Stream object.OpenStandardInput() Overloaded Returns the standard input stream as a Stream object.OpenStandardOutput() Overloaded Returns the standard output stream as a Stream

object

Read() Reads the next character from the standard input stream

ReadLine() Reads the next line of characters as a string from Console, which

is set to the system’s standard input stream by default

SetError() Redirects the Errorproperty to use the specified TextWriter

string userInput = System.Console.ReadLine();

System.Console.WriteLine (“You said : “ + userInput);

}

}

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 32

The previous code is much shorter and easier to digest in comparison to its Java counterpart One usefulthing you’ll get with the Console.WriteLine()static method is the ability to use formatted strings.The flexibility of formatted strings can be illustrated by writing a simple game where user input is used

to generate a story Here is the code for this game, EchoGame:

class EchoGame{

static void Main(string[] args){

System.Console.WriteLine(“Name of a country?”);

string userInput1 = System.Console.ReadLine();

System.Console.WriteLine(“Name of a young prince?”);

string userInput2 = System.Console.ReadLine();

System.Console.WriteLine(“What was the prince doing?”);

string userInput3 = System.Console.ReadLine();

System.Console.WriteLine(“What did he find while doing this?”);

string userInput4 = System.Console.ReadLine();

System.Console.WriteLine(“Then what did he do?”);

string userInput5 = System.Console.ReadLine();

System.Console.WriteLine(“Once upon a time in”

+ “ {0}, there was a young prince {1},\n” +

“who while {2}, came across a {3}, and then “+ “{4} ! “, userInput1, userInput2,

userInput3, userInput4, userInput5 );

}}

The insertion points are replaced by the supplied arguments starting from the index {0}, which sponds to the leftmost variable (in this case userInput1) You are not limited to supplying only stringvariables, nor are you confined to using just variables, or even using variables of the same type Anytype that the method WriteLine()can display can be supplied as an argument, including string literals

corre-or actual values There is also no limit to the number of insertion points that can be added to the string,

as long as it is less than the overall number of arguments Note that omitting insertion points from thestring will cause the variable not to be displayed You must, however, have an argument for each inser-tion point you specify whose index in the argument list corresponds to the index of the insertion point

In the following listing, for example, removing {1}is fine as long as there are still three arguments Inthis case {0}matches up with strAand {2}matches up with strC:

Console.WriteLine(“hello {0} {1} {2}”, strA, strB, strC);

Summar yMicrosoft describes C# as a simple, modern language derived from C and C++ Because Java is also amodernization of C++, much of the syntax and inbuilt features present in C# are also available in Java

C# uses.NET Framework, and so offers built-in, type-safe, object-oriented code that is interoperable withany language that supports the Common Type System (CTS) Java does offer interoperability with C andC++, but it is not type-safe Moreover, it is highly complex

1251

C# for Java Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 33

C# namespaces provide a much more flexible way of grouping related classes C# filenames are notbound to the classes within them as they are in Java, nor are namespace names bound to folders as pack-age names are in Java C# also provides a rich set of built-in value types, including type-safe enumera-tions, structures, and the built-in primitives that offer a robust alternative to Java’s primitives.

C# provides bi-directional conversion between reference and value types called boxing and unboxing.

This functionality is not supported in Java C# supports the use of classes, complete with fields, structors, and methods, as a template for describing types, and provides the ability to define destructors,methods called just before the class is garbage collected C# also provides three approaches to methodparameters—in(default), out, or ref

con-C# also introduces the concept of method hiding, as well as supporting explicit overriding with the virtualand overridekeywords, and C# provides properties as an alternative to get()and set()methods as a way to access safely internal fields

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 34

C# for C++ Developer s

This appendix is intended for developers who are already familiar with C++ and want to see whatthe differences are between C++ and C# We will survey the C# language, noting specifically thoseareas in which it is different from C++ Because the two languages do have a large amount of syn-tax and methodology in common, advanced C++ programmers may find they can use thisappendix as a shortcut to learning C#

It should be made clear that C# is a distinct language from C++ Whereas C++ was designed forgeneral object-oriented programming in the days when the typical computer was a standalonemachine running a command-line-based user interface, C# is designed specifically to work with.NET and is geared to the modern environment of Windows and mouse-controlled user interfaces,networks, and the Internet There is a similarity between the two languages, particularly in syntax,and this is not surprising since C# was designed as an object-oriented language that took the goodpoints of earlier object-oriented languages—of which C++ has been arguably the most successfulexample—but learned from the poorer design features of these languages

Because of the similarities between the two languages, developers who are fluent in C++ may findthat the easiest way to learn C# is to treat it as C++ with a few differences and learn what thosedifferences are This appendix is designed to help you do that

We will start off with a broad overview, mentioning, in general terms, the main differences betweenthe two languages, but also indicating what areas they have in common We follow this by compar-ing what the standard Hello, World program looks like in each of the two languages The bulk of theappendix is dedicated to a topic-by-topic analysis that looks at each of the main language areas andgives a detailed comparison between C# and C++; inevitably, an appendix of this size cannot be com-prehensive, but we will cover all the main differences between the languages that you will notice inthe course of everyday programming It is worth pointing out that C# relies heavily on support fromthe NET base class library in a large number of areas In this appendix we will largely restrict ourattention to the C# language itself, and not extensively cover the base classes

For the purposes of comparison, we are taking ANSI C++ as our reference point Microsoft has addednumerous extensions to C++, and the Windows Visual C++ compiler has a few incompatibilities withSimpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 35

the ANSI standard, which we’ll occasionally point out, but we will not normally use these when comparing

the two languages

Conventions for This Appendix

Note that in this appendix we adopt an additional convention when displaying code; C# code will

always be displayed with gray shading:

int X; // this is interesting

However, any C++ code presented for comparison will be presented like this, without any shading:

// this is C++ code

class CMyClass : public CMyBaseClass

{

In the sample code in this appendix we have also taken account of the most common naming

conven-tions when using the two languages under Windows Hence class names in the C++ examples begin

with Cwhile the corresponding names in the C# examples do not Also, Hungarian notation is often

used for variable names in the C++ samples only

Terminology

You should be aware that a couple of language constructs have a different terminology in C# from that

in C++ Member variables in C++ are known as fields in C# while functions in C++ are known as methods

in C# In C#, the term function has a more general meaning and refers to any member of a class that

con-tains code This means that “function” covers methods, properties, constructors, destructors, indexers,

and operator overloads In C++, “function” and “method” are often used interchangeably in casual

speech, though strictly a C++ method is a virtual member function

If this all sounds confusing, the following table should help

Any item in a class that contains instructions Function (or member function) Function

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 36

Meaning C++ Term C# Term

Item in a class that contains instructions and is Function (or member function) Methodcallable by name with the syntax DoSomething

In this appendix we will, where possible, use the terminology appropriate to the language we arediscussing

A Comparison of C# and C++

In this section we’ll briefly summarize the overall differences and similarities between the twolanguages

Differences

The main areas in which C# differs from C++ are as follows:

Compile target—C++ code usually compiles to assembly language C# by contrast compiles to

intermediate language (IL), which has some similarities to Java byte code The IL is subsequently

converted to native executable code by a process of Just-In-Time (JIT) compilation The emitted

IL code is stored in a file or set of files known as an assembly An assembly essentially forms the

unit in which IL code, along with metadata, is packaged, corresponding to a DLL or executablefile that would be created by a C++ compiler

Memory management—C# is designed to free the developer from memory management keeping tasks This means that in C# you do not have to explicitly delete memory that was allo-cated dynamically on the heap, as you would in C++ Rather, the garbage collector periodicallycleans up memory that is no longer needed In order to facilitate this, C# does impose certainrestrictions on how you can use variables that are stored on the heap, and is stricter about typesafety than C++

book-❑ Pointers—Pointers can be used in C# just as in C++, but only in blocks of code that you havespecifically marked for pointer use For the most part, C# relies on Visual Basic/Java-style refer-ences for instances of classes, and the language has been designed in such a way that pointersare not required nearly as often as they are in C++

1255

C# for C++ Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 37

Operator overloads—C# does not allow you to explicitly overload as many operators as C++.This is largely because the C# compiler automates this task to some extent by using any avail-able custom overloads of elementary operators (like =) to work out overloads of combined oper-ators (+=) automatically.

Library—Both C++ and C# rely on the presence of an extensive library For ANSI C++ this is thestandard library C# relies on a set of classes known as the NET base classes The NET baseclasses are based on single inheritance, whereas the standard library is based on a mixture ofinheritance and templates Also, whereas ANSI C++ keeps the library largely separate from thelanguage itself, the interdependence in C# is much closer, and the implementation of many C#keywords is directly dependent on particular base classes

Target environments—C# is specifically designed to target programming needs in GUI-basedenvironments (not necessarily just Windows, although the language currently only supportsWindows), as well as background services such as Web services This doesn’t really affect thelanguage itself, but is reflected in the design of the base class library C++ by contrast wasdesigned for more general use in the days when command-line user interfaces were dominant.Neither C++ nor the standard library include any support for GUI elements On Windows, C++developers have had to rely directly or indirectly on the Windows API for this support

Preprocessor directives—C# has some preprocessor directives, which follow the same overallsyntax as in C++ But in general there are far fewer preprocessor directives in C#, since other C#language features make these less important

Enumerators—These are present in C#, but are much more versatile than their C++ equivalents,since they are syntactically fully fledged structs in their own right, supporting various proper-ties and methods Note that this support exists in source code only—when compiled to nativeexecutables, enumerators are still implemented as primitive numeric types, so there is noperformance loss

Destructors—C# cannot guarantee when class destructors are called In general, you should notuse the programming paradigm of placing code in C# class destructors, as you can in C++, unlessthere are specific external resources to be cleaned up, such as file or database connections Sincethe garbage collector cleans up all dynamically allocated memory, destructors are not so impor-tant in C# as they are in C++ For cases in which it is important to clean up external resources assoon as possible, C# implements an alternative mechanism involving the IDisposableinterface

Classes versus structs—C# formalizes the difference between classes (typically used for largeobjects with many methods) and structs (typically used for small objects that comprise littlemore than collections of variables) Among other differences, classes and structs are storeddifferently, and structs do not support inheritance

Similarities

Areas in which C# and C++ are very similar include:

Syntax—The overall syntax of C# is very similar to that of C++, although there are numerousminor differences

Execution flow—C++ and C# both have roughly the same statements to control flow of tion, and these generally work in the same way in the two languages

execu-Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 38

Exceptions—Support for these in C# is essentially the same as in C++, except that C# allowsfinally blocks and imposes some restrictions on the type of object that can be thrown.

Inheritance model—Classes are inherited in the same way in C# as in C++ Related conceptssuch as abstract classes and virtual functions are implemented in the same way, although thereare some differences in syntax Also, C# supports only single inheritance of classes, but multipleinterface inheritance The similarity in class hierarchy incidentally means that C# programs willnormally have a very similar overall architecture to corresponding C++ programs

Constructors—Constructors work in the same way in C# as in C++, though again there aresome differences in syntax

New Features

C# introduces a number of new concepts that are not part of the ANSI C++ specification (although most

of these have been introduced by Microsoft as non-standard extensions supported by the Microsoft C++compiler) These are:

Delegates—C# does not support function pointers However, a similar effect is achieved bywrapping references to methods in a special form of class known as a delegate Delegates can bepassed around between methods and used to call the methods to which they contain references,

in the same way that function pointers can be in C++ What is significant about delegates is thatthey incorporate an object reference as well as a method reference This means that, unlike afunction pointer, a delegate contains sufficient information to call an instance method in a class

Events—Events are similar to delegates, but are specifically designed to support the callbackmodel, in which a client notifies a server that it wants to be informed when some action takesplace C# uses events as a wrapper around Windows messages in the same way that VisualBasic does

Properties—This idea, used extensively in Visual Basic and in COM, has been imported into C#

A property is a method or get/set pair of methods in a class that have been dressed up cally, so to the outside world it looks like a field Properties allow you to write code likeMyForm.Height = 400instead of MyForm.SetHeight(400)

syntacti-❑ Interfaces—An interface can be thought of as an abstract class, whose purpose is to define a set

of methods or properties that classes can agree to implement The idea originated in COM C#interfaces are not the same as COM interfaces; they are simply lists of methods and propertiesand such, whereas COM interfaces have other associated features such as GUIDs, but the princi-ple is very similar This means that C# formally recognizes the principle of interface inheritance,whereby a class inherits the definitions of functions, but not any implementations

Attributes—C# allows you to decorate classes, methods, parameters, and other items in codewith meta-information known as attributes Attributes can be accessed at runtime and used todetermine the actions taken by your code

New Base Class Features

The following features are new to C# and have no counterparts in the C++ language However, supportfor these features comes almost entirely from the base classes, with little or no support from the C#

1257

C# for C++ Developers

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 39

language syntax itself Therefore we will not cover them in this appendix (For more details see Chapters

10 and 15.)

Threading—The C# language includes some support for thread synchronization, via the lockstatement (C++ has no inbuilt support for threads and you have to call functionality in codelibraries.)

Reflection—C# allows code to obtain information dynamically about the definitions of classes

in compiled assemblies (libraries and executables) You can actually write a program in C# thatdisplays information about the classes and methods that it is made up from!

Unsupported Features

The following parts of the C++ language do not have any equivalent in C#:

Multiple inheritance of classes—C# classes support multiple inheritance only for interfaces

Templates—These are not part of the C# language at present, although Microsoft has stated that

it is investigating the possibility of template support for future versions of C#

The Hello Wor ld Example

Writing a Hello World application is far from original, but a direct comparison of Hello World in C++and C# can be quite instructive for illustrating some of the differences between the two languages Inthis comparison we’ve tried to innovate a bit (and demonstrate more features) by displaying “HelloWorld!”both at the command line and in a message box We’ve also made a slight change to the text ofthe message in the C++ version, in a move which we emphasize should be interpreted as a bit of funrather than a serious statement

The C++ version looks like this:

cout << “Goodbye, World!”;

MessageBox(NULL, “Goodbye, World!”, “”, MB_OK);

Trang 40

{static int Main(string[] args){

Console.WriteLine(“Hello, World!”);

MessageBox.Show(“Hello, World!”);

return 0;

}}}

Comparing the two programs tells us that the syntax of the two languages is quite similar In particular,code blocks are marked off with braces ({ }), and semicolons are used as statement delimiters LikeC++, C# ignores all excess whitespace between statements We’ll go through the samples line by line,examining the features they demonstrate

libraries, achieved by passing command-line parameters to the linker C# doesn’t really separate ing and linking in the way that C++ does In C#, the command-line parameters are all that is required(and only then if you are accessing anything beyond the basic core library) By themselves, these willallow the compiler to find all the class definitions; hence explicit references in the source code are unnec-essary This is actually a much simpler way of doing it—and indeed once you’ve familiarized yourselfwith the C# model, the C++ version, in which everything needs to be referred to twice, starts to lookrather strange and cumbersome

compil-One other point we should note is that of the two #includestatements in the above C++ code, the firstaccesses an ANSI standard library (the iostreampart of the standard library) The second is a

Windows-specific library, and is referenced in order that we can display the message box C++ code onWindows often needs to access the Windows API because the ANSI standard doesn’t have any window-ing facilities By contrast, the NET base classes—in a sense, the C# equivalent of the ANSI standard tem-plate library—do include windowing facilities, and only the NET base classes are used here Our C#code requires no non-standard features (Although arguably, this point is balanced by the fact that stan-dard C# is only available on Windows, at present.)

Although the C# code above happens not to have any #includedirectives, it’s worth noting that somepreprocessor directives (though not #include) are available in C#, and do retain the #syntax

Ngày đăng: 13/08/2014, 15:21

TỪ KHÓA LIÊN QUAN