Preface

The C# language was released by Microsoft as one of the core languages for developing .NET applications. C# bears amazing similarities to Sun Microsystems' Java programming language. But along with the similarities there are a slew of differences and deviations in the overall programming methodology, syntax, and constructs. In your enthusiasm to transfer your Java skills to C#, it is easy to overlook these differences. Each language has its own good coding practices, and good Java coding practices are not necessarily good C# coding practices. The intent of this book is to bring home the fundamentals of C# from the perspective of a Java programmer. We expose the differences in the two languages while underscoring good C# coding practices.

How This Book Is Different

This book was written by programmers for programmers, and hence you will find the book to be light on description and heavy on code. You will note a preponderance of complete code samples to illustrate C# concepts, constructs, syntax, and philosophies. Where possible, we provide Java listings. The code listings are fairly nontrivial at times, and we have tried to explain concepts by walking through code. This approach is similar to some of the Java open source project tutorials out there.

As a Java programmer you will notice that we look at Java quirks and idioms to explore whether they also exist in C#. We have also examined some features of C# to discover why they don't exist in Java and why they are designed differently in C#. In places, we give coding practices in Java that are rendered redundant in C#. For example, using the + operator to concatenate strings and create large strings has been heavily denounced in the Java world, but it is not necessarily a bad thing in C#.

We have given each chapter its unique set of code listings instead of building one massive application throughout the book. Note, too, that the book focuses on discussing the C# language and not the associated tools that come with the .NET development environment.

Who Should Read This Book?

As the title suggests, this book is tailored to suit typical Java programmers. Those who regularly program in Java should have a short C# learning curve after reading this book. If you haven't programmed in Java, you should be familiar with the fundamentals of object-oriented programming (OOP) and should have programmed with an OOP language such as C++ or Smalltalk. If you are not familiar with OOP, we suggest you hone your OOP skills and get comfortable with working with classes, interfaces, objects, and polymorphism, and then revisit C#.

Overview of Chapters

Although you are welcome to consult any random chapter as a reference for understanding its C# concept, we recommend reading the chapters in order. In that way, you won't get bogged down by syntax and construct questions when it comes to discussing the more esoteric APIs. Following is a brief description of each chapter.

Chapter 1, The .NET Framework, is an overview of the various components of the .NET framework. Readers itching to code can skip this chapter.

Chapter 2, Starting with C#, explores the proverbial Hello World program—first without using the Visual Studio .NET integrated development environment (IDE), and then using the IDE. We briefly explain the components of the IDE. Knowledge of the IDE is important if you are to develop large-scale enterprise applications. However, you don't need to be well versed in the IDE to understand the language concepts.

Chapter 3, C# and Java: What Is the Difference?, lists the features of C# and compares them to equivalent features in Java. This chapter makes for good reading for those who want to quickly know how C# differs from Java.

Chapter 4, Writing Objects, gets down to the business end of OOP: writing objects. Java programming is all about writing classes.

Chapter 5, Understanding Inheritance and Polymorphism, looks at the cornerstones of any OOP language. Both Java and C# use a single-root class hierarchy and have polymorphism. As a Java programmer you have probably been pampered by Java's always turned-on, automatic virtual dispatching. The C# approach is to have virtual dispatching turned off by default. What does that mean to you as a Java programmer? This chapter illustrates some C# pitfalls that Java programmers might fall into if they are not careful.

Chapter 6, Implementing Interfaces, explains that both Java and C# allow a class to implement multiple interfaces. We discuss several aspects of a C# interface.

Chapter 7, Data Types, explores the elements that make a programming language. C# provides a lot more data types and constructs than Java does. You should read this chapter if you want to exploit C#-specific constructs and not end up writing everything as a class in C#.

Chapter 8, Operators, covers a fairly mundane, but important, topic. You may be surprised to learn that C# supports operator overloading.

Chapter 9, Essential Control Flow, discusses control flow statements such as if-then-else, switch, for, foreach, and many more. C# is a very expressive language that contains built-in optimizations of some constructs. You will learn that C# allows strings in switch statements, along with many other surprising details.

Chapter 10, Programming with Exceptions, treats something that used to be an option in C++ and is now a major part of the Java language. Fortunately, C# and Java both agree on making exception handling a core part of the language. Unfortunately, there is no throws clause in C#. So how do you know which exceptions are thrown by a method you call? As a Java programmer you might find C#'s lenient exception handling both a blessing and a curse.

Chapter 11, Working with Arrays, explains this fundamental data structure, which is found in any programming language. C# goes a step further than most languages by having a special class for arrays.

Chapter 12, Processing Strings, deals with one of the most ubiquitous classes of Java, which also happens to be commonplace in C#. This chapter discusses the fundamental concepts of string equality, interning, and optimizations.

Chapter 13, Formatting Numbers, Strings, and Dates, discusses the C# equivalent of the java.text.* package.

Chapter 14, Using Collections, explains how both Java and C# collections let you build an automobile without reinventing the wheel. Unfortunately, the C# collection library is currently no match for what Java has to offer.

Chapter 15, Working with the C# I/O API, discusses I/O streams, files, directories, and serialization. C# makes a distinction between a file and a directory, and it gives you several ways to make a class serializable.

Chapter 16, Thread Programming, shows you how C# has simplified threading. You can finally close threads in C#, and it gives you a system-supplied thread pool—and this means no more scrambling for third-party implementations. You can have reader-writer locks on resources, something the JDK does not provide out of the box. C# also gives you four different ways to write multithreaded classes. Many more surprises unfold in this chapter.

Chapter 17, Using C# Properties, Indexers, and Attributes, may bring back memories long forgotten for Java programmers who once were Visual Basic programmers. Properties reduce code clutter by eliminating getter and setter calls. Indexers let you treat collections as arrays, and attributes let you tinker with the metadata of your code. None of these features is supported in Java.

Chapter 18, Delegates and Event Programming, explains how function pointers, abandoned in Java, are back in C# as delegates. Here's another example of how C# goes out of its way to not model every concept or construct as a class.

Chapter 19, Accessing Databases, deals with a capability that is part of the core .NET API. A unique C# data structure is the RowSet object, which is basically an in-memory representation of an RDBMS table or view. This chapter discusses some of the routine database operations that you will want to execute.

Chapter 20, Processing XML, reveals that XML processing, which has finally made it into the core API in Java 1.4, is a first-class concept in C#. You get built-in support for XML, XSL translation, and XPath in C#'s core libraries.

Chapter 21, GUI Programming in C#, is brimming with practical advice for GUI builders. The Java Swing library has become the preferred API for building client-side Java GUI applications. The Swing library consists of classes modeled after the MVC (model view controller) pattern. Although very modular, Swing can be tedious to work with because the JDK does not ship with a GUI designer. This makes it a chore to design rich, interactive screens because everything must be coded by hand. Only recently have third-party Java IDEs become available to simplify Swing programming. In contrast, the .NET Windows Forms library is reminiscent of Visual Basic drag-and-drop Forms, with event-driven code associated with the controls on the form. If you have the Visual Studio .NET handy, then GUI programming in C# is reduced to drag-and-drop and adding event-based code. The Visual Studio .NET Forms Designer is a welcome change for languishing Swing programmers.

Chapter 22, Reflection, explains that reflective capabilities go hand in hand with managed code and type-safe data types. Reflection allows you to probe the metadata behind the various language constructs. Both C# and Java provide a great set of reflection API classes. But C#'s reflection emit feature takes the cake because it lets you dynamically generate and run MSIL code.

Chapter 23, Assemblies, Application Configuration, and Process Management, argues that packaging is everything. This is true even for computer applications. An improperly packaged and deployed application either will not work or will give you runtime headaches. C# assemblies let you deploy complex applications as one unit that can be versioned. C# also provides several deep hooks into Windows operating system process management. Read all about assemblies and processes in this chapter.

The Code Style Used in This Book

Code conventions vary, and you should stick to the convention followed by your programming team or organization. Here, we differentiate code from the regular text by using a different font style (code). We avoid Hungarian notation for variable names and instead use the Java style. For example, we use

int count;

instead of

int m_IntCount;

Method names follow Pascal casing instead of Java's camel casing. So the Java method name

getName()

would be translated as

GetName()

Loops and control flow statements follow a slanting style, where open braces appear at the end of the line and close braces appear at the beginning of the line:

for (int  i = 0; i < 100; i++) {
//Code goes here
}

We have commented the code in strategic places where it is not obvious why a particular approach was taken. We feel that the code should be as self-explanatory as possible. This can be achieved by giving meaningful names to variables and methods so that the intent of the method is conveyed without additional comments. For example, the intent of the following method is obvious:

public void PrintProperties(object o)

The code listings revolve around explaining one or two concepts. We have tried to maintain the focus of the code listing while keeping it interesting. When a concept does not deserve a full-blown class, we use code snippets.

From the Authors to You

Writing this book has been a great learning experience for us. We were pleasantly surprised to discover that C# is not very different from Java, with a few exceptions. As a Java programmer, you should consider yourself equipped with the basic strategies, patterns, and idioms that you are used to coding in the Java world, because you can easily carry over most of these practices into the C# world.

The main difference we have discovered between the two languages is that Java emphasizes consistency by modeling everything as a class, whereas C# has many more programming constructs that are not classes: enums, structs, properties, indexers, delegates, and pointers. This means that you can continue to model everything as a class in C#, but if you do that you will rob yourself of the benefit of exploiting the built-in efficiencies in some of the C# constructs. These constructs also make the resulting code a little bit more expressive. With this in mind, we have encouraged you wherever possible to use the C# style.

Finally, we encourage you to play with the Visual Studio .NET IDE. It is not necessary to use it to program in C#, but we recommend it because it will help you crank out applications and reduce some of the tedium of designing a lot of big applications fast.

Acknowledgments

I don't think I could have written this book by myself without my co-author, Alok Pota. Alok is really an amazing person who constantly inspires me. I still remember the day I met him back in 1994. When I first met him I said to myself, “He is really the guy with whom I can constantly talk about technology.” Even today I don't remember talking to him about anything but technology. I would like to thank senior acquisitions editor Sondra Scott, with whom we really enjoyed working. I consider myself very lucky to have met Sondra, so thanks to Larry Wall (my former manager) for introducing me to Sondra. Thanks to Laurie McGuire and Jennifer Blackwell, who did a wonderful job in making sure the content was well organized and consistent. Thanks to Mark Burhop, Howard Lee Harkness, and Kevin T. Price for all the hard work they have done in providing the right feedback. Thanks to the production team Amy Fleischer and Betsy Hardinger for their diligent and meticulous work.

I would like to thank my colleagues at Nucor Corporation, who understood when I said, “I need to leave in 10 minutes to work on the book,” and my manager, Scott Messenger, for giving me an opportunity to work on exciting projects related to Microsoft technology. I would also like to personally thank Chris Osborne for his help and for giving me his spiteful habit of assembling computers rather than buying them from a store.

Special thanks are due to my wonderful wife, Anjani, for keeping up with my crazy long nights and weekend work schedules, and to my mom, dad, sisters, and brother for their support.

—Jawahar

Putting together a book is a lot of work. I would like to express my gratitude to several people for their help with this endeavor. First and foremost, I would like to thank Sondra Scott, senior acquisitions editor at Addison-Wesley Professional, for affording me the chance to join the ranks of Addison-Wesley authors. It's a great honor, and no small responsibility.

I have known my co-author, Jawahar Puvvala, for several years now. We have always been keen on trying out new technology. We have often discussed the similarities and differences between C# and Java. We decided to take these arguments a step further and thoroughly examine the differences. I am thankful for those moments of geek talk, which ignited my curiosity about C# and fueled my passion for writing this book.

Authors of technical books rely heavily on technical reviewers to detect errors and omissions. I would like to thank Mark Burhop, Howard Lee Harkness, and Kevin T. Price for giving this book a critical review. We have incorporated several of their suggestions. The development editors and production team, Jennifer Blackwell, Laurie McGuire, Betsy Hardinger, and Amy Fleischer, worked tirelessly to make sure the book was on the right track.

I have had the honor of working with many talented people during my career as a programmer. I would like to particularly thank my peers in the Core Technologies Group at Digital Motorworks LP for making me a part of their group. Their passion for programming perfection and writing good clean code is contagious, and they have made me a better programmer. Last but not least, I would like to thank my wife, Suzy, whose kind and patient attitude allowed me to accomplish this work. My parents have always been a source of encouragement for me, and although they are miles away from me, their guidance has helped me achieve my goals.

Alok

About the Authors

Jawahar Puvvala has been developing enterprise applications in Sun and Microsoft technologies for variety of high-tech companies for the past five years. Jawahar is a consultant at Nucor Corporation in Charlotte, North Carolina. It was structural engineering that made Jawahar a programming expert; his educational background is in writing matrix analysis software for mechanical and structural engineering systems in C++. Today, he specializes in client-server and distributed application development in various technologies and languages, including COM+, MFC, ATL, ASP, MSMQ, XML, XSLT, DCOM, SOAP, C++, C#, Java, and Visual Basic. He has published a couple of journal and conference articles on structural engineering.

Jawahar wrote his first enterprise-level application in Java for the textile industry. Although he is not an obsessively 100 percent pure Java programmer, he thinks that it was the interface programming concepts in Java that laid the foundation for his success in COM/DCOM in Microsoft technology.

When he is not working, he spends his time taking care of his house and home network. He can be reached at [email protected].

Alok Pota is a Java addict currently working as a J2EE application developer at Digital Motorworks (DMi) in Austin, Texas. Alok has been developing server-side enterprise applications using J2EE technologies for the past five years and is always seeking out the latest and greatest in Java technology. Before working with Java, his expertise was in writing scientific numerical analysis and visualization software in Visual C++, Visual Basic, and FORTRAN. Alok's published work includes numerous scientific articles on mathematical modeling and expert systems.

Alok began his career in programming by writing numerical modeling software in C++. Coupled with his modeling skills and his interest in the field of artificial intelligence, this experience helped him to write a decision support system based on the expert system shell CLIPS (C Language Integrated Production Systems). When he was introduced to Java, he switched gears from writing scientific software to writing business-related software.

When not reading up on Java or tinkering with the latest APIs, Alok likes to play with his son, Rajiv. You can reach Alok at [email protected].

About the Technical Reviewers

Mark Burhop is a senior software engineer in Cincinnati, Ohio, and also a member of the adjunct faculty at the University of Cincinnati. He has more than 15 years of experience developing software in the computer aided engineering and product data management fields using technologies ranging from Microsoft .NET (C#) to Java to C++. As an author, he is currently focused on showing how to write high-performance C# applications. More information on Mark and his work can be found at http://www.markburhop.com.

Howard Lee Harkness has earned a living writing software in more than a dozen different languages, and teaching other programmers, for nearly three decades. He holds a degree in computer science from the University of Texas and has worked with many kinds of software, ranging from embedded systems in military and automotive applications to Web-based bill-of-materials systems. In his spare time, he plays the violin at Irish sessions.

Kevin T. Price is a senior technologist in Vienna, Virginia, specializing in security and scalability, and he has worked with all aspects of application development within the Microsoft toolset for several years. He has also written chapters for or edited several books related to XML, security, and .NET technologies. When not sitting at a computer, Kevin can frequently be found either in a kitchen or on a paintball field. He can be reached at [email protected].

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.82.79