From Java to C#: A Developer's Guide: Allows Java developers to learn C# quickly by highlighting the differences and similarities between the two languages Contains extensive detailed co
Trang 2absent in Java are given the detailed description they warrant.
This practical guide will help you move easily from Java and J2EE to C# and NET concepts as quickly
as possible.
From Java to C#: A Developer's Guide:
Allows Java developers to learn C# quickly by highlighting the differences and similarities
between the two languages
Contains extensive detailed coverage of features
in C# that are not found in Java
Has a useful introduction to the NET platform and explains how the new architecture works
Illustrated throughout with a wealth of code
examples which are short yet comprehensive.
Trang 6Section 6.9.
Nested classes (Java inner classes) Chapter 7.
Destructors
Section 7.6.
Trang 8Section 10.1.
Operators and their precedence in C#
Trang 10Multi-dimensional arrays: jagged arrays Section 12.4.
Mixing jagged and rectangular arrays Section 12.5.
Using the System.Array class
Trang 13Section 20.3.
Inheritance of properties
Trang 15#else and #elif
Trang 17Section 29.9.
Using the -> member access operator Section 29.10.
Using the sizeof operator
Trang 19Abbreviations used in this book
Trang 20British Library Cataloguing in Publication Data A CIP catalogue record for this book can be obtained from the British Library Library of Congress Cataloging-in-Publication Data Mok, Heng Ngee.
Trang 21Copyright Licensing Agency Ltd, 90 Tottenham Court Road, London W1P4LP This book may not be lent, resold, hired out or otherwise disposed of
The Publishers' policy is to use paper manufactured from sustainable forests.
Dedication
This book goes to my ever-caring Mum, and my darling Siew Leng
Not forgetting our dear 'fighting hamsters' who accompanied me throughthe night while I was hacking away at the computer: Hammok, Hammie,Hamzel, and the late Hammy
Trang 22Heng Ngee Mok is an experienced developer who has been involved innumerous large-scale software enterprise projects based on J2EE
Besides development work, Heng Ngee holds ad hoc training classes forJava and J2EE technology He lectures regularly at Nanyang
Polytechnic's School of IT, a tertiary institution in Singapore
Heng Ngee writes frequently for Computer Times, a weekly local IT
newspaper and has been invited to speak at Microsoft's Developer
Festival and the official launch of Visual Studio NET in Singapore Hewas awarded Most Valuable Professional status by Microsoft Asia at thefirst Asia MVP Summit held at Shanghai
As well as being a Sun Certified Programmer for Java 2, a Sun CertifiedWeb Component Developer for J2EE, and a Microsoft Certified SystemsEngineer, Heng Ngee holds a first degree in computer engineering, and
is completing his thesis for his postgraduate degree in communicationssoftware and networks
Heng Ngee lives in cosmopolitan and equatorial (read "warm and humid")Singapore He enjoys nature trekking, lazing in bed with a good book,tinkering with the latest technical toys (he can't cultivate this habit to thefullest because of a meagre income), and poking his nose into foreigncultures on backpacking trips Contact him at mok@ieee.org both to offercomments about this book, or if you intend to visit his country on a
shoestring budget
Trang 23My first real contact with NET started late in 2001 Since March 2000, Ihave been hosting a fortnightly Java-related column sponsored by Sun
Microsystems (Singapore) in the Computer Times A friend from
Microsoft Singapore approached me and handed me a CD containing thebeta version of VS NET so that I could take a look at it and 'maybe writesomething interesting' if I so desired
Of course by that time I had already heard of this new infrastructure fromMicrosoft Microsoft had been marketing NET aggressively for ages, and
enabled' languages (including modified versions of Eiffel and even
COBOL) Nevertheless you can forget about all except those that camebundled with VS NET and are supported by Microsoft I suppose yourproject manager will not be very pleased if you submit your (albeit
working) NET module in COBOL codes
Of the three, I chose C# This is a powerful object-oriented language withits roots in C++ and Java (Officially, C# has been touted as the offspring
of C and C++ only Despite the fact that Java isn't mentioned once in theC# Language Specification and other Microsoft literature, it is quite
evident that the makers of C# had indeed studied and `inherited´ somefeatures from Java.) With C#, you can do anything that can possibly bedone within the NET CLR VB NET is a significant improvement over VB
6 with the addition of real object-oriented features such as class
inheritance and polymorphic method invocation Nevertheless, there are
Trang 24.NET program C# allows the developer to write unsafe codes You can't
do that with VB NET or J# The creators of NET had written huge
chunks of the NET BCLs using C# itself To me, C# means lots of power,while VB NET is Microsoft's way of allowing VB 6 developers to migrate
to NET with as little pain as possible J#, on the other hand, reeks ofVisual J++'s failure
Learning a new programming language from scratch can be an awesometask Imagine learning a whole new development platform or multi-tieredinfrastructure! Nevertheless, it should be noted that most parallel (or
competing) technologies are based on similar computer science
concepts, and it will be much easier to learn, say, a new object-orientedprogramming language once you have a good foundation in another
object-oriented programming language (assuming you really understandthe fundamental concepts behind object-oriented technology)
During my experimentation with NET Beta, I realized that learning theCLR is easy if you already know what a JVM is Similarly, picking up ASP.NET is easier if you have done JSP programming before
As I was learning about NET, I couldn't help but compare the differencesbetween C# and Java, ASP NET and JSP, the CLR and the JVM, NETand the J2EE framework I am an experienced Java developer and
trainer, and as I was reading through books and documentation, I couldn'thelp noticing that C# and Java are syntactically very similar I could haveskipped a significant portion of the text - if only I knew which sections toskip
I didn't want to read about how to use the switch/case keywords in C#again because I already knew that from my Java knowledge All I wanted
to know was that in C#, switch can take in not only numeric types butstrings too That's the difference, and that's all that I needed to know if Iwanted to use the switch/case keywords in a C# program I had toread a whole paragraph just to understand one small point If only therewas a book which highlighted just the differences between C# and Java!Later that year, Microsoft invited me to a public forum and lecture during
Trang 25programming language, familiarity with the Java syntax, and experiencewith basic coding concepts such as exception handling and object-
oriented programming
I have tried to present each section using clear simple examples[1] thatare short and to the point Each section is meant to be quite independent
of others, and where such dependent knowledge is required to
understand a particular point, I state so I have assumed that it is yourresponsibility to integrate all the knowledge gained in the separate
sections to make use of the language's features in a complex
complementary way My code examples will avoid doing that for claritypurposes
[1] Have you ever seen tutorial examples which require you to have extensive knowledge
of another topic? Such examples really irritate me I don't like to read long pieces of code just to understand a simple principle, and that's why I have tried to keep my code
examples short yet comprehensive.
In order not to clutter up the real meat of each section, I have placed mypersonal observations, comments, and URLs where you can obtain morerelevant information in footnotes
I hope you find learning about C# and NET as enriching an experience
as mine
Trang 26H.N Mok (mok@ieee.org)July 2002
Trang 27Trademarks
Structure of the book
Trang 28Targeted audience
This book is meant for Java developers who want to learn the C#
language as quickly as possible Basic familiarity with the Java languagesyntax and semantics, and an academic foundation in object-orientedprogramming are assumed (Don't worry, you don't have to be an expert!And you don't need to read this book with a Java reference companion.)
Trang 29In order to try out the C# codes in this book, you will need a copy of NETSDK[2] or VS NET from Microsoft The NET SDK and NET Frameworkwill be installed when you install VS NET If you are not using VS NET,you may want to get a color-coded text editor instead of using Notepadfor coding purposes
[2] Can be downloaded from http://msdn.microsoft.com/netframework
Trang 30important NET BCLs used for multi-threading, file I/O, reflectionoperations, and some useful collection classes
What is not covered:
use of other NET BCLs;
use of C# for web services, web forms (ASP NET), graphics (GDI+),COM interoperability, database access (ADO NET);
other NET issues such as NET security and remoting
Trang 32At the time of writing, a fully working implementation of C# in VS NEThas just been released The C# codes shown in this book have beencompiled and tested using the command line C# compiler (csc.exe) ofthe first final release version of VS NET
Trang 33Expensive chocolate, fine wines, and generous praise are also welcome.You can find the latest erratum list at www.mokhengngee.per.sg/book.
Trang 34".NET", "Visual Studio NET", "Visual C# NET", "Visual Basic NET" aretrademarks of Microsoft Corporation "Java" is a trademark of Sun
Microsystems
Trang 35Part 2 : Classes, methods, and other OO stuff
This part discusses how C# handles classes, namespaces, methods,constructors, and variables Object-oriented related issues are coveredhere
Part 3 : Types, operators, and flow control
The language semantics and syntax of C# are almost identical withJava's This part is written such that you can skim through it relativelyquickly to appreciate the differences
Part 4 : Core topics
Topics covered in this part include arrays, event handling, exceptionhandling, reflection, multi-threading, the collection classes, and file I/O
These are major topics which often warrant a huge separate chapter in
other C# books This book does not go through the basic ideas but does
Trang 36Part 5 : Convenience features
Convenience features[3] are C# features which are good to have but notessential Basically they help increase programmer productivity by
providing shortcuts for the normal ways of doing things Topics coveredinclude C# properties, indexes, operator overloading, and user-definedconversions These will all be new topics to a Java developer
Convenience features do not increase the power of a language, but justmake it more convenient for a good programmer to use it Like a double-edged sword, convenience features steepen the learning curve
significantly, but give the programmer more elegant ways to accomplishtasks
[3] I think I am the originator of the term 'convenience features' I haven't read any
literature using that term for C# properties, indexes, and the like.
Part 6 : C#-specific features
This part describes features found in C# which have no equivalents inJava Topics include C# preprocessor directives, attributes, structures,enums, and unsafe coding Care has been taken to write this part clearly,
so that it is simple to understand yet comprehensive
Part 7 : Appendices
There are six appendices Here you will find the full list of C# keywords,and their closest equivalents in Java I have also included C# codingconventions (a good starting point even before coding commences), auseful summary on how to write XML documentation (which resembles
Trang 37the Javadoc comments) and a short write-up on NET assemblies Themany (necessary) abbreviations are also defined here - as opposed tothe missable first-time definitions sometimes given in the text.
Trang 38I would like to show my appreciation to the following friends Without theirassistance, encouragement, and influence this book would never havematerialized They are (in no particular order):
Viki Williams, Senior Acquisitions Editor for Addison-Wesley (andavid English football fan) for all your patience and assistance
The editorial team and anonymous reviewers working hard at
Addison-Wesley for picking out all those bugs and errors which I had(intentionally and unintentionally) embedded in the original
manuscript
Grace, Hellen and Badi of Computer Times, Special Projects Team
at Singapore Press Holdings Writing for you guys opened up newworlds And Jenny, thanks for introducing me to technical journalism
K.C at Microsoft Singapore for getting me involved with the whole.NET thing, and introducing me to Microsoft's culture
Dr Ng Wee Keong, my academic mentor during my days at NanyangTechnological University
Yixing, Jianhao, Fuzan, Zongrong, and the rest of the NPCC guys
My former classmates Bruce, Robert, Wanwen, Meili, and the lateZhenqiang It has been more than a decade of friendship!
Kelvin (aka Cilin), Mathematics whiz and Windows 2000 expert Iwould not have got that distinction for that Math paper if not for yourcoaching (you didn't think I would remember that, did you?)
My former colleagues at National Computer Systems where I started
Trang 39on Java (despite 'being permanently busy') during the years I wasmastering that language; Yam Khoon, Chee Ying, Ben, Ghim Howe,Charles, Yong Kwan, Sufen, Otneil, Boon, Amanda, and our PM AhHock thanks for providing me with a good learning environment;Joyce, Bee Ling, Jianwei, and Jiansong thanks for going through thefour-month long IT project management lesson
My other family members staying under the same roof who have totolerate my vampirish life style
Trang 40Introduction
This part serves as an introduction to the rest of the book Though
it is possible not to mention anything about NET in a book aboutC# (C# is a standard in its own right), I would suggest at least arudimentary understanding of Microsoft's grand NET plan
Knowing what NET is all about and the role that C# plays in itgives a good 'big picture' view and an appreciation of why C# hasbeen designed in certain ways
Chapters 1 and 2 give a whirlwind introduction to the world of.NET, including some other NET-related technologies, withoutgoing into details Important concepts such as how CLR works arecovered in Chapter 1 I have also taken the liberty of includingsome personal opinions about the C# language in Chapter 2
J# is briefly introduced in Chapter 3 Although this book is aboutC#, it will be useful to be at least acquainted with J#, especiallysince you have a Java background
Part 1 ends with the all important "Hello World" program If this isthe first time you have met this new language, I highly recommendgoing through the Hello World exercise before continuing with theother parts of this book
The chapters in this part are:
• Chapter 1: Introducing NET
• Chapter 2: Introducing C#
Trang 41• Chapter 3: JUMP to NET and J#
• Chapter 4: Hello C#!