Gift Guide

Effective C#: 50 Specific Ways to Improve Your C# [NOOK Book]


C#'s resemblances to C++, Java, and C make it easier to learn, but there's a downside: C# programmers often continue to use older techniques when far better alternatives are available. In Effective C#, respected .NET expert Bill Wagner identifies fifty ways you can start leveraging the full power of C# in order to write faster, more efficient, and more reliable software.

Effective C# follows the format that made Effective C++ (Addison-Wesley, 1998) and Effective Java ...

See more details below
Effective C#: 50 Specific Ways to Improve Your C#

Available on NOOK devices and apps  
  • NOOK Devices
  • Samsung Galaxy Tab 4 NOOK 7.0
  • Samsung Galaxy Tab 4 NOOK 10.1
  • NOOK HD Tablet
  • NOOK HD+ Tablet
  • NOOK eReaders
  • NOOK Color
  • NOOK Tablet
  • Tablet/Phone
  • NOOK for Windows 8 Tablet
  • NOOK for iOS
  • NOOK for Android
  • NOOK Kids for iPad
  • PC/Mac
  • NOOK for Windows 8
  • NOOK for PC
  • NOOK for Mac

Want a NOOK? Explore Now

NOOK Book (eBook)
$27.49 price
(Save 42%)$47.99 List Price


C#'s resemblances to C++, Java, and C make it easier to learn, but there's a downside: C# programmers often continue to use older techniques when far better alternatives are available. In Effective C#, respected .NET expert Bill Wagner identifies fifty ways you can start leveraging the full power of C# in order to write faster, more efficient, and more reliable software.

Effective C# follows the format that made Effective C++ (Addison-Wesley, 1998) and Effective Java (Addison-Wesley, 2001) indispensable to hundreds of thousands of developers: clear, practical explanations, expert tips, and plenty of realistic code examples. Drawing on his unsurpassed C# experience, Wagner addresses everything from value types to assemblies, exceptions to reflection. Along the way, he shows exactly how to avoid dozens of common C# performance and reliability pitfalls. You'll learn how to:

  • Use both types of C# constants for efficiency and maintainability, see item 2
  • Use immutable data types to eliminate unnecessary error checking, see item 7
  • Avoid the C# function that'll practically always get you in trouble, see item 10
  • Minimize garbage collection, boxing, and unboxing, see items 16 and 17
  • Take full advantage of interfaces and delegates, see items 19 though 22
  • Create CLS compliant assemblies that use noncompliant C# language features, see item 30
  • Improve reliability and maintainability by creating small, cohesive assemblies, see item 32
  • Leverage the full power of .NET's runtime diagnostics, see item 36
  • Know when–and when not–to use reflection, see items 42 and 43
  • Preview the major enhancements in C# 2.0, see item 49
  • You're already a successful C# programmer–this book can help you become an outstanding one.

Bill Wagner is co-founder of and .NET consultant for SRT Solutions. A nationally recognized independent expert on .NET, he has been a regular contributor to ASP.NET Pro Magazine, Visual Studio Magazine, and the .NET Insight newsletter. In addition to being a Microsoft Regional Director, he is also active in the Southeast Michigan .NET User Group and the Ann Arbor Computing Society. He is author of The C# Core Language Little Black Book (The Coriolis Group, 2002).

© Copyright Pearson Education. All rights reserved.

Read More Show Less

Editorial Reviews

From Barnes & Noble
The Barnes & Noble Review
C# isn’t C++ or Java. Your old habits could be holding you back. In Effective C#, Bill Wagner brings together 50 new C# idioms and techniques that accelerate development, improve code quality, and enhance performance and scalability.

Wagner’s solutions cover core language elements, .NET resource management, binary component development, more effective expression of program design, and many other topics. Sometimes he focuses on features that exist only in C#, elegantly addressing problems that previous languages didn’t handle well. Elsewhere, he shows why older techniques don’t work the way you expect in C# (for example, in garbage collection).

Wagner’s an outstanding writer for working programmers in a hurry. He’s crisp, concise, well organized. You’ll get a lot of “bang” for the time you invest with this 300-page book. Bill Camarda, from the February 2005 Read Only
If you're interested in, or currently working with, .NET and are tempted to skip past this book as Just Another C# Reference Book, think again. Wagner's book is a great resource because it covers concepts which run across the entire .NET Framework regardless of which language you're working with. ...The bottom line: this book really is a critical addition to a serious C# or .NET developer's bookshelf.
Read More Show Less

Product Details

  • ISBN-13: 9780321630162
  • Publisher: Pearson Education
  • Publication date: 12/17/2004
  • Series: Effective Software Development Series
  • Sold by: Barnes & Noble
  • Format: eBook
  • Edition number: 1
  • Pages: 336
  • Sales rank: 865,092
  • File size: 359 KB

Table of Contents


1. C# Language Elements.

Item 1 - Always Use Properties Instead of Accessible Data Members.

Item 2 - Prefer readonly to const.

Item 3 - Prefer the is or as Operators to Casts.

Item 4 - Use Conditional Attributes Instead of #if.

Item 5 - Always Provide ToString().

Item 6 - Distinguish Between Value Types and Reference Types.

Item 7 - Prefer Immutable Atomic Value Types.

Item 8 - Ensure That 0 Is a Valid State for Value Types.

Item 9 - Understand the Relationships Among ReferenceEquals(),static Equals(), instance Equals(), and operator==.

Item 10 - Understand the Pitfalls of GetHashCode().

Item 11 - Prefer foreach Loops.

2. .NET Resource Management.

Item 12 - Prefer Variable Initializers to Assignment Statements.

Item 13 - Initialize Static Class Members with Static Constructors.

Item 14 - Utilize Constructor Chaining.

Item 15 - Utilize using and try/finally for Resource Cleanup.

Item 16 - Minimize Garbage.

Item 17 - Minimize Boxing and Unboxing.

Item 18 - Implement the Standard Dispose Pattern.

3. Expressing Designs with C#.

Item 19 - Prefer Defining and Implementing Interfaces to Inheritance.

Item 20 - Distinguish Between Implementing Interfaces and Overriding Virtual Functions.

Item 21 - Express Callbacks with Delegates.

Item 22 - Define Outgoing Interfaces with Events.

Item 23 - Avoid Returning References to Internal Class Objects.

Item 24 - Prefer Declarative to Imperative Programming.

Item 25 - Prefer Serializable Types.

Item 26 - Implement Ordering Relations with IComparable and Icomparer.

Item 27 - Avoid Icloneable.

Item 28 - Avoid Conversion Operators.

Item 29 - Use the new Modifier Only When Base Class Updates Mandate It.

4. Creating Binary Components.

Item 30 - Prefer CLS-Compliant Assemblies.

Item 31 - Prefer Small, Simple Functions.

Item 32 - Prefer Smaller, Cohesive Assemblies.

Item 33 - Limit Visibility of Your Types.

Item 34 - Create Large-Grain Web APIs.

5. Working with the Framework.

Item 35 - Prefer Overrides to Event Handlers.

Item 36 - Leverage .NET Runtime Diagnostics.

Item 37 - Use the Standard Configuration Mechanism.

Item 38 - Utilize and Support Data Binding.

Item 39 - Use .NET Validation.

Item 40 - Match Your Collection to Your Needs.

Item 41 - Prefer DataSets to Custom Structures.

Item 42 - Utilize Attributes to Simplify Reflection.

Item 43 - Don't Overuse Reflection.

Item 44 - Create Complete Application-Specific Exception Classes.

6. Miscellaneous.

Item 45 - Prefer the Strong Exception Guarantee.

Item 46 - Minimize Interop.

Item 47 - Prefer Safe Code.

Item 48 - Learn About Tools and Resources.

Item 49 - Prepare for C# 2.0.

Item 50 - Learn About the ECMA Standard.


Read More Show Less


This book is designed to offer practical advice for the programmer on how to improve productivity when using the C# language and the .NET libraries. In it, I have comprised 50 key items, or minitopics, related to the most-frequently-asked questions that I (and other C# consultants) have encountered while working with the C# community.

I started using C# after more than 10 years of C++ development, and it seems that many C# developers are following suit. Throughout the book, I discuss where following C++ practices may cause problems in using C#. Other C# developers are coming to the language with a strong Java background; they may find some of these passages rather obvious. Because some of the best practices change from Java to C#, I encourage Java developers to pay special attention to the discussions on value types (see Chapter 1, "C# Language Elements"). In addition, the .NET Garbage Collector behaves differently than the JVM Garbage Collector (see Chapter 2, ".NET Resource Management").

The items in this book are the collection of recommendations that I most often give developers. Although not all items are universal, most of the items can be easily applied to everyday programming scenarios. These include discussions on Properties (Item 1), Conditional Compilation (Item 4), Immutable Types (Item 7), Equality (Item 9), ICloneable (Item 27), and the new Modifier (Item 29). It has been my experience that, in most situations, decreasing development time and writing good code are the primary goals of the programmer. Certain scientific and engineering applications may place the highest premium on the overall performance of the system. Still, for others, it's all about the scalability. Depending on your goals, you might find particular information more (or less) relevant under certain circumstances. To address this, I have tried to explain the goals in detail. My discussions on readonly and const (Item 2), Serializable Types (Item 25), CLS Compliance (Item 31), Web Methods (Item 34), and DataSets (Item 41) assume certain design goals. Those goals are spelled out in these items, so that you can decide what is most applicable for you in your given situation.

Although each item in Effective C# stands alone, it is important to understand that the items have been organized around major topics, such as C# language syntax, resource management, and object and component design. This is no accident. My goal is to maximize learning the material covered in the book by leveraging and building each item on earlier items. Don't let that keep you from using it as a reference, though. If you have specific questions, this book functions well as the ideal "ask-me" tool. Please keep in mind that this is not a tutorial or a guide to the language, nor is it going to teach you C# syntax or structure. My goal is to provide guidance on the best constructs to use in different situations.

Who Should Read this Book?

Effective C# is written for professional developers, those programmers who use C# in their daily work lives. It assumes that you have some experience with object-oriented programming and at least one language in the C family: C, C++, C#, or Java. Developers with a Visual Basic 6 background should be familiar with both the C# syntax and object-oriented design before reading this book. Additionally, you should have some experience with the major areas of .NET: Web Services, ADO.NET, Web forms, and Windows Forms. I reference these concepts throughout the book.

To fully take advantage of this book, you should understand the way the .NET environment handles assemblies, the Microsoft Intermediate Language (MSIL), and executable code. The C# compiler produces assemblies that contain MSIL, which I often abbreviate as IL. When an assembly is loaded, the Just In Time (JIT) Compiler converts that MSIL into machine-executable code. The C# compiler does perform some optimizations, but the JIT compiler is responsible for many more effective optimizations, such as inlining. Throughout the book, I've explained which process is involved in which optimizations. This two-step compilation process has a significant effect on which constructs perform best in different situations.

About the Content

Chapter 1,"C# Language Elements," discusses the C# syntax elements and the core methods of System.Object that are part of every type you write. These are the topics that you must remember every day when you write C# code: declarations, statements, algorithms, and the System.Object interface. In addition, all the items that directly relate to the distinction between value types and reference types are in this chapter. Many items have some differences, depending on whether you are using a reference type (class) or a value type (struct). I strongly encourage you to read the discussions on value and reference types (Items 6 through 8) before reading deeper into the book.

Chapter 2, ".NET Resource Management," covers resource management with C# and .NET. You'll learn how to optimize your resource allocation and usage patterns for the .NET managed execution environment. Yes, the .NET Garbage Collector makes your life much simpler. Memory management is the environment's responsibility, not yours. But, your actions can have a big impact on how well the Garbage Collector performs for your application. And even if memory is not your problem, nonmemory resources are still your responsibility; they can be handled through IDisposable. You'll learn the best practices for resource management in .NET here.

Chapter 3, "Expressing Designs with C#," covers object-oriented design from a C# perspective. C# provides a rich palette of tools for your use. Sometimes, the same problems can be solved in many ways: using interfaces, delegates, events, or attributes and reflection. Which one you pick will have a huge impact on the future maintainability of your system. Choosing the best representation of your design will help to make it easier for the programmers using your types. The most natural representation will make your intent clearer. Your types will be easier to use and harder to misuse. The items in Chapter 3 focus on the design decisions you will make and when each C# idiom is most appropriate.

Chapter 4, "Creating Binary Components," covers components and language interoperability. You'll learn how to write components that can be consumed by other .NET languages, without sacrificing your favorite C# features. You'll also learn how to subdivide your classes into components in order to upgrade pieces of your application. You should be able to release new versions of a component without redistributing the entire application.

Chapter 5, "Working with the Framework," covers underutilized portions of the .NET Framework. I see a strong desire in many developers to create their own software rather than use what's already been built. Maybe it's the size of the .NET Framework that causes this; maybe it's that the framework is completely new. These items cover the parts of the framework where I have seen developers reinvent the wheel rather than use what they've been given. Save yourself the time by learning how to use the framework more efficiently.

Chapter 6, "Miscellaneous," finishes with items that did not fit in the other categories and with a look forward. Look here for C# 2.0 information, standards information, exception-safe code, security, and interop.

A Word About the Items

My vision for these items is to provide you with clear and succinct advice for writing C# software. Some guidelines in the book are universal because they affect the correctness of a program, such as initializing data members properly (see Chapter 2). Others are not so obvious and have generated much debate in the .NET community, such as whether to use ADO.NET DataSets. While I personally believe that using them is a great timesaver (see Item 41), other professional programmers, whom I highly respect, disagree. It really depends on what you're building. My position comes from a timesaving stance. For others who write a great deal of software that transfer information between .NET- and Java-based systems, DataSets are a bad idea. Throughout the book, I support and have given justification for all the suggestions I make. If the justification does not apply to your situation, neither does the advice. When the advice is universal, I usually omit the obvious justification, which is this: Your program won't work otherwise.

Regarding C# 2.0

I say little about the upcoming C# 2.0 release; there are two reasons for this. First and foremost, most of the advice in this book applies just as well for C# 2.0 as it does for the current version. Although C# 2.0 is a significant upgrade, it is built on C# 1.0 and does not invalidate most of today's advice. Where the best practices will likely change, I've noted that in the text.

The second reason is that it's too early to write the most effective uses of the new C# 2.0 features. This book is based on the experience I've had--and the experience my colleagues have had--using C# 1.0. None of us has enough experience with the new features in C# 2.0 to know the best ways to incorporate them into our daily tasks. I'd rather not mislead you when the simple fact is that the time to cover the new C# 2.0 features in an Effective book has not yet arrived.

Read More Show Less


Effective C#


This book is the result of all the questions I've answered for readers, consulting clients, and at various .NET user group meetings. Effective C# is not an introduction to the C# Language, or .NET programming. Rather, this book is meant for professional C# developers that are interested in becoming more productive with the C# language. With that in mind, throughout the book I assume that you have some working knowledge of C#, and the core .NET Framework. This book will show you the techniques that experienced C# programmers always use, or almost always avoid. We follow these practices because we've learned. We've learned the hard way, by fixing our own code when we didn't follow these practices. Or, we've learned the easy way, by listening to the advice of others.

This book is your chance to learn the easy way. With a great deal of help (and some argument) from a fantastic group of colleagues and technical reviewers, this book shows you the techniques we follow and why. In each item I give you a specific piece of advice that the best C# programmers use, and explain the rationale behind that advice.

This book is not a how-to, or a cookbook that contains large volumes of sample code that produces particular features. You will not find sample programs that you can use for your particular programming tasks. In fact, I have tried to limit the length of each code listing to better highlight the techniques I am illustrating in that item.

I started writing C# programs after spending close to ten years developing C++ programs. I know the switch from native,unmanaged development to a managed environment was one of the biggest adjustments I made when I started working with C#. To that end, I'm certain that some of the advice in this book is colored by that experience. Those items might seem obvious to a reader with a strong Java background. But, it's clear to me from working with the C# community that developers come to C# from different backgrounds: VB 6 (or earlier), Java, and C++ developers comprise the largest segments. I tried to keep the advice centered on C# and the .NET environment and away from migrating from one particular language to another. My goal was to write Effective C# so that no matter what path brought you to the C# language, this book will help you do your best development, now that you are here.


The biggest difficulty writing a book about a programming language is that language designers take real English words and give them a very specific new meaning. It makes for passages that can be tough to understand: "Develop interfaces with interfaces,"as an example. Anytime I use a specific language keyword, it is in the code style. When I discuss general topics with specific C# concepts, the specific C# topic is capitalized, as in: "Create Interfaces to represent the interface supported by your classes."It's still not perfect, but it should make many of these passages easier to read.

There are many related C# terms used in this book. When I refer to a member of type, it refers to any definition that can be part of a type: methods, properties, fields, indexers, events, enums or delegates. When only some apply, I use a more specific term: property, method, data field, delegate.

Finally, there are a number of terms that may or may not already be familiar to you. New terms appear in bold for the first time.

Code Conventions

The code samples in this book are small, focused examples that illustrate one technique, or the pitfalls associated with not following the recommended technique. I've omitted many details from each listing. In most cases, you should assume the presence of common using clauses:

using Systm;using System.IO;using System.Collections;using System.Data;

Omitting these saves us both time: I did not have to write these at the top of every sample. You don't have to read it at the top of every sample. When I use less common namespaces, I make sure you can see the relevant namespace. I use fully qualified class names in very short samples. I include the less common using statements in larger samples.

I take similar liberties with code inside the samples. For example, I'll show this:

string s1 = GetMessage( );

However, I may not show the body of the GetMessage( ) routine if it's not relevant to the discussion. Whenever I omit code, you can assume that the missing method does something obvious and reasonable. My purpose in this is to keep us both focused on the particular topic. By omitting code that is not part of that topic, neither of us gets distracted.

With those omissions, you will not be able to type the code samples and get a running sample. However, all the code is syntactically correct.

A Word about advice and goals

Your design goals have a strong bearing on how best to implement a solution to a particular problem. In most situations, decreasing development time is the primary goal. Some applications, notably compact framework applications, will consider space the primary goal. Scientific and Engineering applications will place the highest premium on the overall performance of the system. Still other times, it's scalability. Depending on your goals, a particular piece of advice may be less relevant. In those cases, I have explained the goals in detail so that you can decide when it applies to you. For example, whether or not to use ADO.NET Datasets has generated much debate in the .NET community. I, for one, believe using them is a great timesaver. Others I highly respect, such as Ted Neward and Clemens Vasters, disagree. It depends on what you're building. I take my position because it saves me time. Both Ted and Clemens write a great deal of software that transfers documents between .NET and Java based systems. Datasets are a bad idea for those systems. Before you blindingly follow my advice, or anyone's for that matter, understand why the advice is there and make sure the justification matches your goals. I've given the justification on all the guidelines in the book.

Of course, some guidelines are universal, because they affect the correctness of your program, such as initializing data members properly. In those cases, I usually omit the obvious justification, which is that your program won't work otherwise.

What about C# 2.0

You'll notice that I say rather little about the upcoming C# 2.0 release. There are two reasons for this. First and foremost, most of the advice in this book will apply just as well for C# 2.0 as it does now. C# 2.0, while a significant upgrade, does not invalidate most of today's advice. Where the best practices will change, I've noted that in the text.

The second reason is that it's too early to write the most effective uses of the C# 2.0 features. As I stated in the beginning of the introduction, this book is based on the experience I've had, and the experience my colleagues have had, using C# 1.0. None of us have as enough experience with C# 2.0 to know the best ways to incorporate the new features into our daily tasks. I'd rather not mislead you and act like I have the answers when the simple fact is that the time to cover C# 2.0 in an Effective book has not yet arrived.

© Copyright Pearson Education. All rights reserved.

Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star


4 Star


3 Star


2 Star


1 Star


Your Rating:

Your Name: Create a Pen Name or

Barnes & Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation


  • - By submitting a review, you grant to Barnes & and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Terms of Use.
  • - Barnes & reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing 1 – 10 of 4 Customer Reviews
  • Anonymous

    Posted April 15, 2010

    No text was provided for this review.

  • Anonymous

    Posted December 28, 2009

    No text was provided for this review.

  • Anonymous

    Posted July 2, 2009

    No text was provided for this review.

  • Anonymous

    Posted August 3, 2010

    No text was provided for this review.

  • Anonymous

    Posted January 24, 2010

    No text was provided for this review.

  • Anonymous

    Posted January 24, 2010

    No text was provided for this review.

  • Anonymous

    Posted January 7, 2010

    No text was provided for this review.

  • Anonymous

    Posted March 22, 2010

    No text was provided for this review.

  • Anonymous

    Posted January 2, 2010

    No text was provided for this review.

  • Anonymous

    Posted December 18, 2009

    No text was provided for this review.

Sort by: Showing 1 – 10 of 4 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)