Framework Design Guidelines

Krzysztof Cwalina, Brad Abrams

Mentioned 56

A new edition of this title is available, ISBN-10: 0321545613 ISBN-13: 9780321545619 "This book is an absolute must-read for all .NET developers. It gives clear do and don't guidance on how to design class libraries for .NET. It also offers insight into the design and creation of .NET that really helps developers understand the reasons why things are the way they are. This information will aid developers designing their own class libraries and will also allow them to take advantage of the .NET class library more effectively." --Jeffrey Richter, author/trainer/consultant, Wintellect "Framework Design Guidelineswill help you in two important ways. First, any .NET developer will benefit from a greater understanding of the design principles that govern the .NET Base Class Library. Second, a deeper understanding of these principles will help you to create software that integrates well with the .NET environment. Quite frankly, this book should be on every .NET developer's bookshelf." --Bill Wagner, founder and consultant, SRT Solutions, author ofEffective C# "Not since Brooks'The Mythical Man Monthhas the major software maker of its time produced a book so full of relevant advice for the modern software developer. This book has a permanent place on my bookshelf and I consult it frequently." --George Byrkit, senior software engineer, Genomic Solutions "This book is a must-read for all architects and software developers thinking about frameworks. The book offers insight into some driving factors behind the design of the .NET Framework. It should be considered mandatory reading for anybody tasked with creating application frameworks." --Peter Winkler, senior software engineer, Balance Technology Inc. "Frameworks are valuable but notoriously difficult to construct: Your every decision must be geared towards making them easy to be used correctly and difficult to be used incorrectly. This book takes you through a progression of recommendations that will eliminate many of those downstream 'I wish I'd known that earlier' moments. I wish I'd read it earlier." --Paul Besly, principal technologist, QA "Filled with information useful to developers and architects of all levels, this book provides practical guidelines and expert background information to get behind the rules.Framework Design Guidelinestakes the already published guidelines to a higher level, and it is needed to write applications that integrate well in the .NET area." --Cristof Falk, software engineer Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Librariesteaches developers the best practices for designing system frameworks and reusable libraries for use with the Microsoft .NET Framework and WinFX. This book focuses on the design issues that directly affect the programmability of a framework, specifically its publicly accessible APIs. This book can improve the work of any .NET developer producing code that other developers will use. An added benefit is a collection of annotations to the guidelines by various members of the Microsoft .NET Framework and WinFX teams, which provide a lively discussion of the motives behind the guidelines, along with examples of good reasons for breaking the guidelines. Microsoft architects Krzysztof Cwalina and Brad Abrams offer guidelines for framework design from the top down. From their long experience and deep insight, you will learn The general philosophy of framework design Principles and guidelines that are fundamental to overall framework design Naming guidelines for the various parts of a framework, such as namespaces, types, and members Guidelines for the design of types and members of types Issues and guidelines that are important to ensure appropriate extensibilityin your framework Guidelines for working with exceptions, the preferred error reporting mechanism in the .NET Framework and WinFX Guidelines for extending and using types that commonly appear in frameworks Guidelines for and examples of common framework design patterns Guidelines in this book come in four major forms:Do,Consider,Avoid, andDo not. In general, aDoguideline should almost always be followed, aConsiderguideline should generally be followed, anAvoidguideline indicates that something is generally not a good idea, and aDo notguideline indicates something you should almost never do. Every guideline includes a discussion of its applicability, and most guidelines include a code example. A companion DVD includes theDesigning .NET Class Librariesvideo series, instructional presentations by the authors on design guidelines for developing classes and components that extend the .NET Framework. A sample API specification and other useful resources are also included.

More on

Mentioned in questions and answers.

What are the differences in implementing interfaces implicitly and explicitly in C#?

When should you use implicit and when should you use explicit?

Are there any pros and/or cons to one or the other?

Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.

I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.

Could anyone touch on that aspect as well?

Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:

public void CopyTo(Array array, int index)
    throw new NotImplementedException();

and explicitly as:

void ICollection.CopyTo(Array array, int index)
    throw new NotImplementedException();

The difference being that implicitly is accessible through your class you created when it is cast as that class as well as when its cast as the interface. Explicit implementation allows it to only be accessible when cast as the interface itself.

MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.

I use explicit primarily to keep the implementation clean, or when I need two implementations. But regardless I rarely use it.

I am sure there are more reasons to use it/not use it that others will post.

See the next post in this thread for excellent reasoning behind each.

It wasn't that long ago that I was a beginning coder, trying to find good books/tutorials on languages I wanted to learn. Even still, there are times I need to pick up a language relatively quickly for a new project I am working on. The point of this post is to document some of the best tutorials and books for these languages. I will start the list with the best I can find, but hope you guys out there can help with better suggestions/new languages. Here is what I found:

Since this is now wiki editable, I am giving control up to the community. If you have a suggestion, please put it in this section. I decided to also add a section for general be a better programmer books and online references as well. Once again, all recommendations are welcome.

General Programming

Online Tutorials
Foundations of Programming By Karl Seguin - From Codebetter, its C# based but the ideas ring true across the board, can't believe no-one's posted this yet actually.
How to Write Unmaintainable Code - An anti manual that teaches you how to write code in the most unmaintable way possible. It would be funny if a lot of these suggestions didn't ring so true.
The Programming Section of Wiki Books - suggested by Jim Robert as having a large amount of books/tutorials on multiple languages in various stages of completion
Just the Basics To get a feel for a language.

Code Complete - This book goes without saying, it is truely brilliant in too many ways to mention.
The Pragmatic Programmer - The next best thing to working with a master coder, teaching you everything they know.
Mastering Regular Expressions - Regular Expressions are an essential tool in every programmer's toolbox. This book, recommended by Patrick Lozzi is a great way to learn what they are capable of.
Algorithms in C, C++, and Java - A great way to learn all the classic algorithms if you find Knuth's books a bit too in depth.


Online Tutorials
This tutorial seems to pretty consise and thourough, looked over the material and seems to be pretty good. Not sure how friendly it would be to new programmers though.
K&R C - a classic for sure. It might be argued that all programmers should read it.
C Primer Plus - Suggested by Imran as being the ultimate C book for beginning programmers.
C: A Reference Manual - A great reference recommended by Patrick Lozzi.


Online Tutorials
The tutorial on seems to be the most complete. I found another tutorial here but it doesn't include topics like polymorphism, which I believe is essential. If you are coming from C, this tutorial might be the best for you.

Another useful tutorial, C++ Annotation. In Ubuntu family you can get the ebook on multiple format(pdf, txt, Postscript, and LaTex) by installing c++-annotation package from Synaptic(installed package can be found in /usr/share/doc/c++-annotation/.

The C++ Programming Language - crucial for any C++ programmer.
C++ Primer Plus - Orginally added as a typo, but the amazon reviews are so good, I am going to keep it here until someone says it is a dud.
Effective C++ - Ways to improve your C++ programs.
More Effective C++ - Continuation of Effective C++.
Effective STL - Ways to improve your use of the STL.
Thinking in C++ - Great book, both volumes. Written by Bruce Eckel and Chuck Ellison.
Programming: Principles and Practice Using C++ - Stroustrup's introduction to C++.
Accelerated C++ - Andy Koenig and Barbara Moo - An excellent introduction to C++ that doesn't treat C++ as "C with extra bits bolted on", in fact you dive straight in and start using STL early on.


FORTH, a text and reference. Mahlon G. Kelly and Nicholas Spies. ISBN 0-13-326349-5 / ISBN 0-13-326331-2. 1986 Prentice-Hall. Leo Brodie's books are good but this book is even better. For instance it covers defining words and the interpreter in depth.


Online Tutorials
Sun's Java Tutorials - An official tutorial that seems thourough, but I am not a java expert. You guys know of any better ones?
Head First Java - Recommended as a great introductory text by Patrick Lozzi.
Effective Java - Recommended by pek as a great intermediate text.
Core Java Volume 1 and Core Java Volume 2 - Suggested by FreeMemory as some of the best java references available.
Java Concurrency in Practice - Recommended by MDC as great resource for concurrent programming in Java.

The Java Programing Language


Online Tutorials - The online documentation for this language is pretty good. If you know of any better let me know.
Dive Into Python - Suggested by Nickola. Seems to be a python book online.


Online Tutorials
perldoc perl - This is how I personally got started with the language, and I don't think you will be able to beat it.
Learning Perl - a great way to introduce yourself to the language.
Programming Perl - greatly referred to as the Perl Bible. Essential reference for any serious perl programmer.
Perl Cookbook - A great book that has solutions to many common problems.
Modern Perl Programming - newly released, contains the latest wisdom on modern techniques and tools, including Moose and DBIx::Class.


Online Tutorials
Adam Mika suggested Why's (Poignant) Guide to Ruby but after taking a look at it, I don't know if it is for everyone. Found this site which seems to offer several tutorials for Ruby on Rails.
Programming Ruby - suggested as a great reference for all things ruby.

Visual Basic

Online Tutorials
Found this site which seems to devote itself to visual basic tutorials. Not sure how good they are though.


Online Tutorials
The main PHP site - A simple tutorial that allows user comments for each page, which I really like. PHPFreaks Tutorials - Various tutorials of different difficulty lengths.
Quakenet/PHP tutorials - PHP tutorial that will guide you from ground up.


Online Tutorials
Found a decent tutorial here geared toward non-programmers. Found another more advanced one here. Nickolay suggested A reintroduction to javascript as a good read here.

Head first JavaScript
JavaScript: The Good Parts (with a Google Tech Talk video by the author)


Online Tutorials
C# Station Tutorial - Seems to be a decent tutorial that I dug up, but I am not a C# guy.
C# Language Specification - Suggested by tamberg. Not really a tutorial, but a great reference on all the elements of C#
C# to the point - suggested by tamberg as a short text that explains the language in amazing depth


nlucaroni suggested the following:
OCaml for Scientists Introduction to ocaml
Using Understand and unraveling ocaml: practice to theory and vice versa
Developing Applications using Ocaml - O'Reilly
The Objective Caml System - Official Manua


Online Tutorials
nlucaroni suggested the following:
Explore functional programming with Haskell
Real World Haskell
Total Functional Programming


wfarr suggested the following:
The Little Schemer - Introduction to Scheme and functional programming in general
The Seasoned Schemer - Followup to Little Schemer.
Structure and Interpretation of Computer Programs - The definitive book on Lisp (also available online).
Practical Common Lisp - A good introduction to Lisp with several examples of practical use.
On Lisp - Advanced Topics in Lisp
How to Design Programs - An Introduction to Computing and Programming
Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp - an approach to high quality Lisp programming

What about you guys? Am I totally off on some of there? Did I leave out your favorite language? I will take the best comments and modify the question with the suggestions.

Java: SCJP for Java 6. I still use it as a reference.


O'Reilly Book:

  1. Real World Haskell, a great tutorial-oriented book on Haskell, available online and in print.

My favorite general, less academic online tutorials:

  1. The Haskell wikibook which contains all of the excellent Yet Another Haskell Tutorial. (This tutorial helps with specifics of setting up a Haskell distro and running example programs, for example.)
  2. Learn you a Haskell for Great Good, in the spirit of Why's Poignant Guide to Ruby but more to the point.
  3. Write yourself a Scheme in 48 hours. Get your hands dirty learning Haskell with a real project.

Books on Functional Programming with Haskell:

  1. Lambda calculus, combinators, more theoretical, but in a very down to earth manner: Davie's Introduction to Functional Programming Systems Using Haskell
  2. Laziness and program correctness, thinking functionally: Bird's Introduction to Functional Programming Using Haskell

Some books on Java I'd recommend:

For Beginners: Head First Java is an excellent introduction to the language. And I must also mention Head First Design Patterns which is a great resource for learners to grasp what can be quite challenging concepts. The easy-going fun style of these books are ideal for ppl new to programming.

A really thorough, comprehensive book on Java SE is Bruce Eckel's Thinking In Java v4. (At just under 1500 pages it's good for weight-training as well!) For those of us not on fat bank-bonuses there are older versions available for free download.

Of course, as many ppl have already mentioned, Josh Bloch's Effective Java v2 is an essential part of any Java developer's library.

Let's not forget Head First Java, which could be considered the essential first step in this language or maybe the step after the online tutorials by Sun. It's great for the purpose of grasping the language concisely, while adding a bit of fun, serving as a stepping stone for the more in-depth books already mentioned.

Sedgewick offers great series on Algorithms which are a must-have if you find Knuth's books to be too in-depth. Knuth aside, Sedgewick brings a solid approach to the field and he offers his books in C, C++ and Java. The C++ books could be used backwardly on C since he doesn't make a very large distinction between the two languages in his presentation.

Whenever I'm working on C, C:A Reference Manual, by Harbison and Steele, goes with me everywhere. It's concise and efficient while being extremely thorough making it priceless(to me anyways).

Languages aside, and if this thread is to become a go-to for references in which I think it's heading that way due to the number of solid contributions, please include Mastering Regular Expressions, for reasons I think most of us are aware of... some would also say that regex can be considered a language in its own right. Further, its usefulness in a wide array of languages makes it invaluable.

C: “Programming in C”, Stephen G. Kochan, Developer's Library.

Organized, clear, elaborate, beautiful.


The first one is good for beginners and the second one requires more advanced level in C++.

I know this is a cross post from here... but, I think one of the best Java books is Java Concurrency in Practice by Brian Goetz. A rather advanced book - but, it will wear well on your concurrent code and Java development in general.


C# to the Point by Hanspeter Mössenböck. On a mere 200 pages he explains C# in astonishing depth, focusing on underlying concepts and concise examples rather than hand waving and Visual Studio screenshots.

For additional information on specific language features, check the C# language specification ECMA-334.

Framework Design Guidelines, a book by Krzysztof Cwalina and Brad Abrams from Microsoft, provides further insight into the main design decisions behind the .NET library.

For Lisp and Scheme (hell, functional programming in general), there are few things that provide a more solid foundation than The Little Schemer and The Seasoned Schemer. Both provide a very simple and intuitive introduction to both Scheme and functional programming that proves far simpler for new students or hobbyists than any of the typical volumes that rub off like a nonfiction rendition of War & Peace.

Once they've moved beyond the Schemer series, SICP and On Lisp are both fantastic choices.

For C++ I am a big fan of C++ Common Knowledge: Essential Intermediate Programming, I like that it is organized into small sections (usually less than 5 pages per topic) So it is easy for me to grab it and read up on concepts that I need to review.

It is a must read for me the night before and on the plane to a job interview.

C Primer Plus, 5th Edition - The C book to get if you're learning C without any prior programming experience. It's a personal favorite of mine as I learned to program from this book. It has all the qualities a beginner friendly book should have:

  • Doesn't assume any prior exposure to programming
  • Enjoyable to read (without becoming annoying like For Dummies /
  • Doesn't oversimplify

For Javascript:

For PHP:

For OO design & programming, patterns:

For Refactoring:


  • C - The C Programming Language - Obviously I had to reference K&R, one of the best programming books out there full stop.
  • C++ - Accelerated C++ - This clear, well written introduction to C++ goes straight to using the STL and gives nice, clear, practical examples. Lives up to its name.
  • C# - Pro C# 2008 and the .NET 3.5 Platform - Bit of a mouthful but wonderfully written and huge depth.
  • F# - Expert F# - Designed to take experienced programmers from zero to expert in F#. Very well written, one of the author's invented F# so you can't go far wrong!
  • Scheme - The Little Schemer - Really unique approach to teaching a programming language done really well.
  • Ruby - Programming Ruby - Affectionately known as the 'pick axe' book, this is THE defacto introduction to Ruby. Very well written, clear and detailed.

To throw exceptions, I usually use built-in exception classes, e.g. ArgumentNullException and NotSupportedException. However, sometimes I need to use a custom exception and in that case I write:

class SlippedOnABananaException : Exception { }
class ChokedOnAnAppleException : Exception { }

and so on. Then I throw and catch these in my code. But today I came across the ApplicationException class - should I be using that instead? What's it for?

It does seem inefficient to have lots of effectively identical Exception classes with different names (I don't usually need any individual functionality). But I dislike the idea of catching a generic ApplicationException and having to use extra code to determine what the error was.

Where should ApplicationException fit in with my code?

The short answer is: nowhere.

It is a relic of the past, where Microsoft intended developers to inherit all their custom exceptions from ApplicationException. Shortly after, they changed their mind and advised that custom exceptions should derive from the base Exception class. See Best Practices for Handling Exceptions on MSDN.

One of the more widely circulated reasons for this comes from an exerpt from Jeffery Richter in Framework Design Guidelines:

System.ApplicationException is a class that should not be part of the .NET Framework. The original idea was that classes derived from SystemException would indicate exceptions thrown from the CLR (or system) itself, whereas non-CLR exceptions would be derived from ApplicationException. However, a lot of exception classes didn't follow this pattern. For example, TargetInvocationException (which is thrown by the CLR) is derived from ApplicationException. So, the ApplicationException class lost all meaning. The reason to derive from this base class is to allow some code higher up the call stack to catch the base class. It was no longer possible to catch all application exceptions.

So there you have it. The executive summary is that ApplicationException is not harmful, just useless.

Having read the threads Is SqlCommand.Dispose enough? and Closing and Disposing a WCF Service I am wondering for classes such as SqlConnection or one of the several classes inheriting from the Stream class does it matter if I close Dispose rather than Close?

I want to clarify this situation.

According to Microsoft guidelines, it's a good practice to provide Close method where suitable. Here is a citation from Framework design guidelines

Consider providing method Close(), in addition to the Dispose(), if close is standard terminology in the area. When doing so, it is important that you make the Close implementation identical to Dispose ...

In most of cases Close and Dispose methods are equivalent. The main difference between Close and Dispose in the case of SqlConnectionObject is:

An application can call Close more than one time. No exception is generated.

If you called Dispose method SqlConnection object state will be reset. If you try to call any method on disposed SqlConnection object, you will receive exception.

That said:

  • If you use connection object one time, use Dispose.
  • If connection object must be reused, use Close method.

It's common to see a _var variable name in a class field. What does the underscore mean? Is there a reference for all these special naming conventions?

With C#, Microsoft Framework Design Guidelines suggest not using the underscore character for public members. For private members, underscores are OK to use. In fact, Jeffrey Richter (often cited in the guidelines) uses an m_ for instance and a "s_" for private static memberss.

Personally, I use just _ to mark my private members. "m_" and "s_" verge on Hungarian notation which is not only frowned upon in .NET, but can be quite verbose and I find classes with many members difficult to do a quick eye scan alphabetically (imagine 10 variables all starting with m_).

What is best practice when creating your exception classes in a .NET solution: To derive from System.Exception or from System.ApplicationException?

The authors of the framework themselves consider ApplicationException worthless:

with a nice follow-up here:

When in doubt, I follow their book Framework Design Guidelines.

The topic of the blog post is further discussed there.


I am relatively new to C# and each time I begin to work on a C# project (I only worked on nearly mature projects in C#) I wonder why there are no inner classes?

Maybe I don't understand their goal. To me, inner classes -- at least private inner classes -- look a lot like "inner procedures" in Pascal / Modula-2 / Ada : they allow to break down a main class in smaller parts in order to ease the understanding.

Example : here is what is see most of the time :

public class ClassA
   public MethodA()
      <some code>
      myObjectClassB.DoSomething(); // ClassB is only used by ClassA
      <some code>

public class ClassB
   public DoSomething()

Since ClassB will be used (at least for a while) only by ClassA, my guess is that this code would be better expressed as follow :

   public class ClassA
      public MethodA()
         <some code>
         myObjectClassB.DoSomething(); // Class B is only usable by ClassA
         <some code>

      private class ClassB
         public DoSomething()

I would be glad to hear from you on this subject - Am I right?

Thanks in advance!

The Framework Design Guidelines has the best rules for using nested classes that I have found to date.

Here's a brief summary list:

  1. Do use nested types when the relationship between type and nested type is such the member-accessibility semantics are desired.

  2. Do NOT use public nested types as a logical group construct

  3. Avoid using publicly exposed nested types.

  4. Do NOT use nested types if the type is likely to be referenced outside of the containing type.

  5. Do NOT use nested types if they need to be instantiated by client code.

  6. Do NOT define a nested type as a member of an interface.

I'm working on an MVVM project, so I have folders in my project like Models, ViewModels, Windows, etc. Whenever I create a new class, Visual Studio automatically adds the folder name to the namespace designation instead of just keeping the project-level namespace. So, adding a new class to the ViewModels folder would result in the namespace, MyProject.ViewModels instead of just MyProject.

When I first encountered this, it annoyed me. My class names are pretty clear, sometimes even containing the name of the folder in them (e.g., ContactViewModel). I quickly found myself manually removing the folder name on the namespaces. I even tried at one point to create a custom class template (see this question), but I couldn't get that to work, so continued doing it manually.

I've begun to wonder, though, if this convention exists for a good reason that I'm just not seeing. I could see it being useful if you for some reason had lots of sets of identical class names organized into folders, but that doesn't seem like a particularly common scenario.


  • Why is it common convention for namespace names to reflect folder structure?
  • Do you abide by this convention? Why?

If you want some solid advice I'd recommend buying Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries which gives you all you need to know from the actual framework design team.

...the goal when naming namespaces is creating sufficient clarity for the programmer using the framework to immediately know what the content of the namespace is likely to be...


And importantly

Do not use the same name for a namespace and a type in that namespace

Fragmenting every 1/2 types into namespaces would not meet the first requirement as you would have a swamp of namespaces that would have to be qualified or used, if you followed the Visual Studio way. For example

Core - Domain - Users - Permissions - Accounts

Would you create

  • MyCompany.Core.Domain.Users
  • MyCompany.Core.Domain.Permissions
  • MyCompany.Core.Domain.Accounts

or just

  • MyCompany.Core.Domain

For Visual Studio's way it would be the former. Also if you use lowercase file/folder naming you're looking at renaming the class each time, as well as making one big namespace tangle.

Most of it is common sense and really down to how you would expect to see the namespaces organised if you were a consumer of your own API or framework.


I am taking a class at my university called "Software Constraints". In the first lectures we were learning how to build good APIs.

A good example we got of a really bad API function is the socket public static void Select(IList checkRead, IList checkWrite, IList checkError, int microseconds); in C#. The function receives 3 lists of sockets, and destroys them making the user have to clone all the sockets before feeding them into the Select(). It also has a timeout (in microseconds) which is an int, that sets the maximum time the server can wait for a socket. The limits of this is +/-35 minutes (because it is an int).


  1. How do you define an API as 'bad'?
  2. How do you define an API as 'good'?

Points to consider:

  • Function names that are hard to remember.
  • Function parameters that are hard to understand.
  • Bad documentation.
  • Everything being so interconnected that if you need to change 1 line of code you will actually need to change hundreds of lines in other places.
  • Functions that destroy their arguments.
  • Bad scalability due to "hidden" complexity.
  • It's required from the user/dev to build wrappers around the API so that it can be used.

Many coding standards and longer documents and even books (Framework Design Guidelines) have been written on this topic, but much of this only helps at a fairly low level.

There is also a matter of taste. APIs may obey every rule in whatever rulebook, and still suck, due to slavish adherence to various in-vogue ideologies. A recent culprit is pattern-orientation, wherein Singleton Patterns (little more than initialized global variables) and Factory Patterns (a way of parameterizing construction, but often implemented when not needed) are overused. Lately, it's more likely that Inversion of Control (IoC) and associated explosion in the number of tiny interface types that adds redundant conceptual complexity to designs.

The best tutors for taste are imitation (reading lots of code and APIs, finding out what works and doesn't work), experience (making mistakes and learning from it) and thinking (don't just do what's fashionable for its own sake, think before you act).

There are several other good answers on this already, so I thought I'd just throw in some links I didn't see mentioned.


  1. "A Little Manual Of API Design" by Jasmin Blanchette of Trolltech
  2. "Defining QT-Style C++ APIs" also Trolltech


  1. "Effective Java" by Joshua Bloch
  2. "The Practice Of Programming" by Kernighan and Pike

It's been discussed before on Stack Overflow that we should prefer attributes to marker interfaces (interfaces without any members). Interface Design article on MSDN asserts this recommendation too:

Avoid using marker interfaces (interfaces with no members).

Custom attributes provide a way to mark a type. For more information about custom attributes, see Writing Custom Attributes. Custom attributes are preferred when you can defer checking for the attribute until the code is executing. If your scenario requires compile-time checking, you cannot comply with this guideline.

There's even an FxCop rule to enforce this recommendation:

Avoid empty interfaces

Interfaces define members that provide a behavior or usage contract. The functionality described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the interface's members. An empty interface does not define any members, and as such, does not define a contract that can be implemented.

If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker, or a way of identifying a group of types. If this identification will occur at runtime, the correct way to accomplish this is to use a custom attribute. Use the presence or absence of the attribute, or the attribute's properties, to identify the target types. If the identification must occur at compile time, then using an empty interface is acceptable.

The article states only one reason that you might ignore the warning: when you need compile time identification for types. (This is consistent with the Interface Design article).

It is safe to exclude a warning from this rule if the interface is used to identify a set of types at compile-time.

Here comes the actual question: Microsoft didn't conform to their own recommendation in the design of the Framework Class Library (at least in a couple cases): IRequiresSessionState interface and IReadOnlySessionState interface. These interfaces are used by the ASP.NET framework to check whether it should enable session state for a specific handler or not. Obviously, it's not used for compile time identification of types. Why they didn't do that? I can think of two potential reasons:

  1. Micro-optimization: Checking whether an object implements an interface (obj is IReadOnlySessionState) is faster than using reflection to check for an attribute (type.IsDefined(typeof(SessionStateAttribute), true)). The difference is negligible most of the time but it might actually matter for a performance-critical code path in the ASP.NET runtime. However, there are workarounds they could have used like caching the result for each handler type. The interesting thing is that ASMX Web services (which are subject to similar performance characteristics) actually use the EnableSession property of the WebMethod attribute for this purpose.

  2. Implementing interfaces are potentially more likely to be supported than decorating types with attributes by third-party .NET languages. Since ASP.NET is designed to be language agnostic, and ASP.NET generates code for types (possibly in a third-party language with the help of CodeDom) that implement the said interfaces based on the EnableSessionState attribute of the <%@ Page %> directive, it might make more sense to use interfaces instead of attributes.

What are the persuasive reasons to use marker interfaces instead of attributes?

Is this simply a (premature?) optimization or a tiny mistake in the framework design? (Do they think reflection is a "big monster with red eyes"?) Thoughts?

Microsoft didn't strictly follow the guidelines when they made .NET 1.0, because the guidelines evolved together with the framework, and some of the rules they didn't learn until it was too late to change the API.

IIRC, the examples you mention belong to BCL 1.0, so that would explain it.

This is explained in Framework Design Guidelines.

That said, the book also remarks that "[A]ttribute testing is a lot more costly than type checking" (in a sidebar by Rico Mariani).

It goes on to say that sometimes you need the marker interface for compile time checking, which isn't possible with an attribute. However, I find the example given in the book (p. 88) unconvincing, so I will not repeat it here.

Do you use singular or plural for enumerations? I think it makes best sense with plural in the declaration

enum Weekdays

... but I think it makes more sense with singular when using the type, e.g.

Weekday firstDayOfWeek = Weekday.Monday;

I read a recommendation somewhere to use singular whith regular enums and plural with flags, but I would like to hear some more pros and cons.

One recommendation comes from the .NET Framework Design Guidelines, page 59-60:

Do use a singular type name for an enumeration, unless its values are bit fields.

public enum ConsoleColor {

Do use a plural type name for an enumeration with bit fields as values, also called a flags enum.

public enum ConsoleModifiers {

This is probably a matter of personal preference, but when do you use properties instead of functions in your code

For instance to get an error log I could say

string GetErrorLog()
      return m_ErrorLog;

or I could

string ErrorLog
     get { return m_ErrorLog; }

How do you decide which one to use? I seem to be inconsistent in my usage and I'm looking for a good general rule of thumb. Thanks.

If there is more than something trivial happening in a property, then it should be a method. For example, if your ErrorLog getter property was actually going and reading files, then it should be a method. Accessing a property should be fast, and if it is doing much processing, it should be a method. If there are side affects of accessing a property that the user of the class might not expect, then it should probably be a method.

There is .NET Framework Design Guidelines book that covers this kind of stuff in great detail.

While certain guidelines state that you should use an interface when you want to define a contract for a class where inheritance is not clear (IDomesticated) and inheritance when the class is an extension of another (Cat : Mammal, Snake : Reptile), there are cases when (in my opinion) these guidelines enter a gray area.

For example, say my implementation was Cat : Pet. Pet is an abstract class. Should that be expanded to Cat : Mammal, IDomesticated where Mammal is an abstract class and IDomesticated is an interface? Or am I in conflict with the KISS/YAGNI principles (even though I'm not sure whether there will be a Wolf class in the future, which would not be able to inherit from Pet)?

Moving away from the metaphorical Cats and Pets, let's say I have some classes that represent sources for incoming data. They all need to implement the same base somehow. I could implement some generic code in an abstract Source class and inherit from it. I could also just make an ISource interface (which feels more "right" to me) and re-implement the generic code in each class (which is less intuitive). Finally, I could "have the cake and eat it" by making both the abstract class and the interface. What's best?

These two cases bring up points for using only an abstract class, only an interface and using both an abstract class and an interface. Are these all valid choices, or are there "rules" for when one should be used over another?

I'd like to clarify that by "using both an abstract class and an interface" that includes the case when they essentially represent the same thing (Source and ISource both have the same members), but the class adds generic functionality while the interface specifies the contract.

Also worth noting is that this question is mostly for languages that do not support multiple inheritance (such as .NET and Java).

As a first rule of thumb, I prefer abstract classes over interfaces, based on the .NET Design Guidelines. The reasoning applies much wider than .NET, but is better explained in the book Framework Design Guidelines.

The main reasoning behind the preference for abstract base classes is versioning, because you can always add a new virtual member to an abstract base class without breaking existing clients. That's not possible with interfaces.

There are scenarios where an interface is still the correct choice (particularly when you don't care about versioning), but being aware of the advantages and disadvantages enables you to make the correct decision.

So as a partial answer before I continue: Having both an interface and a base class only makes sense if you decide to code against an interface in the first place. If you allow an interface, you must code against that interface only, since otherwise you would be violating the Liskov Substitution Principle. In other words, even if you provide a base class that implements the interface, you cannot let your code consume that base class.

If you decide to code against a base class, having an interface makes no sense.

If you decide to code against an interface, having a base class that provides default functionality is optional. It is not necessary, but may speed up things for implementers, so you can provide one as a courtesy.

An example that springs to mind is in ASP.NET MVC. The request pipeline works on IController, but there's a Controller base class that you typically use to implement behavior.

Final answer: If using an abstract base class, use only that. If using an interface, a base class is an optional courtesy to implementers.

Update: I no longer prefer abstract classes over interfaces, and I haven't for a long time; instead, I favour composition over inheritance, using SOLID as a guideline.

(While I could edit the above text directly, it would radically change the nature of the post, and since a few people have found it valuable enough to up-vote it, I'd rather let the original text stand, and instead add this note. The latter part of the post is still meaningful, so it would be a shame to delete it, too.)

Whenever i override a method of a base class, other than my implementation of this method, i seem to have 3 choices.

1) Call base.Method(), and then provide my implementation.

2) Provide my implementation and then call base.Method()

3) Just provide my implementation.

Recently while using a library i have realized few bugs that were introduced because of not implementing the method as expected by the library. I am not sure if that is bad on part of library, or something wrong in my understanding.

I will take one example.

public class ViewManager {
     public virtual void Customize(){

public class PostViewManager {
     public override void Customize(){

public class PreViewManager {
     public override void Customize(){

public class CustomViewManager {
     public override void Customize(){

My question here is that how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class? Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?

This is why I feel virtual methods are dangerous when you ship them in a library. The truth is you never really know without looking at the base class, sometimes you have to fire up reflektor, read documentation or approach it with trial and error.

When writing code myself I've always tired to follow the rule that says:

Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.

This is taken from, however this is for Event design though I believe I read this in the Framework Design Guidelines book (

However, this is obviously not true, ASP.NET web forms for example require a base call on Page_Load.

So, long and short, it varies and unfortunately there is no instant way of knowing. If I'm in doubt I will omit the call initially.

I'm reading data in from a file and creating objects based on this data. The data format is not under my control and is occasionally corrupt. What is the most appropriate way of handling these errors when constructing the objects in C#?

In other programming languages I have returned a null, but that does not appear to be an option with C#.

I've managed to figure out the following options, but I would appreciate advice from more experienced C# programmers:

Option 1. Read the file inside the constructor and throw an exception when the source data is corrupt:

    obj = Constructor(sourceFile);
    ... process object ...
catch (IOException ex)

Option 2. Create the object, then use a method to read data from the source file:

obj = Constructor();
if (obj.IsValid)
    ... process object ...

or possibly throw exceptions on error:

obj = Constructor();
    ... process object ...

Option 3. Create the object using a static TryParse method:

if (ObjClass.TryParse(sourceFile, out obj))
    ... process object ...

and if so, should I implement option 3 internally using option 1?

public static bool TryParse(FileStream sourceFile, out ObjClass obj)
        obj = Constructor(sourceFile);
        return true;
    catch (IOException ex)
        return false;

From Microsoft Constructor Design Guidelines (MSDN),

Do throw exceptions from instance constructors if appropriate.

Constructors should throw and handle exceptions like any method. Specifically, a constructor should not catch and hide any exceptions that it cannot handle.

Factory Method is not the right way to approach this problem. See Constructors vs Factory Methods

From Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries

5.3 Constructor Design

Consider using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construction of a new instance, or if following the constructor design guidelines feels unnatural.

Do throw exceptions from instance constructors if appropriate.

.NET BCL implementations do throw exceptions from constructors

For example, the List Constructor (Int32), throws an ArgumentOutOfRangeException when the capacity argument of the list is negative.

var myList = new List<int>(-1); // throws ArgumentOutOfRangeException

Similarly, your constructor should throw an appropriate type of exception when it reads the file. For example, it could throw FileNotFoundException if the file does not exist at the specified location, etc.

More Information

Is it possible to somehow mark a System.Array as immutable. When put behind a public-get/private-set they can't be added to, since it requires re-allocation and re-assignment, but a consumer can still set any subscript they wish:

public class Immy
    public string[] { get; private set; }

I thought the readonly keyword might do the trick, but no such luck.

The Framework Design Guidelines suggest returning a copy of the Array. That way, consumers can't change items from the array.

// bad code
// could still do Path.InvalidPathChars[0] = 'A';
public sealed class Path {
   public static readonly char[] InvalidPathChars = 
      { '\"', '<', '>', '|' };

these are better:

public static ReadOnlyCollection<char> GetInvalidPathChars(){
   return Array.AsReadOnly(badChars);

public static char[] GetInvalidPathChars(){
   return (char[])badChars.Clone();

The examples are straight from the book.

In the IDisposable.Dispose method is there a way to figure out if an exception is being thrown?

using (MyWrapper wrapper = new MyWrapper())
    throw new Exception("Bad error.");

If an exception is thrown in the using statement I want to know about it when the IDisposable object is disposed.

James, All wrapper can do is log it's own exceptions. You can't force the consumer of wrapper to log their own exceptions. That's not what IDisposable is for. IDisposable is meant for semi-deterministic release of resources for an object. Writing correct IDisposable code is not trivial.

In fact, the consumer of the class isn't even required to call your classes dispose method, nor are they required to use a using block, so it all rather breaks down.

If you look at it from the point of view of the wrapper class, why should it care that it was present inside a using block and there was an exception? What knowledge does that bring? Is it a security risk to have 3rd party code privy to exception details and stack trace? What can wrapper do if there is a divide-by-zero in a calculation?

The only way to log exceptions, irrespective of IDisposable, is try-catch and then to re-throw in the catch.

    // code that may cause exceptions.
catch( Exception ex )
    // CLR always tries to execute finally blocks

You mention you're creating an external API. You would have to wrap every call at your API's public boundary with try-catch in order to log that the exception came from your code.

If you're writing a public API then you really ought to read Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (Microsoft .NET Development Series) - 2nd Edition .. 1st Edition.

While I don't advocate them, I have seen IDisposable used for other interesting patterns:

  1. Auto-rollback transaction semantics. The transaction class would rollback the transaction on Dispose if not already committed.
  2. Timed code blocks for logging. During object creation a timestamp was recorded, and on Dispose the TimeSpan was calculated and a log event was written.

* These patterns can be achieved with another layer of indirection and anonymous delegates easily and without having to overload IDisposable semantics. The important note is that your IDisposable wrapper is useless if you or a team member forget to use it properly.

Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the EventHandler/EventArgs practice, but what I like to do is have something like:

public delegate void EventHandler<T>(object src, EventArgs<T> args);

public class EventArgs<T>: EventArgs {

  private T item;

  public EventArgs(T item) {
    this.item = item;

  public T Item {
    get { return item; }

Later, I can have my

public event EventHandler<Foo> FooChanged;

public event EventHandler<Bar> BarChanged;

However, it seems that the standard for .NET is to create a new delegate and EventArgs subclass for each type of event. Is there something wrong with my generic approach?

EDIT: The reason for this post is that I just re-created this in a new project, and wanted to make sure it was ok. Actually, I was re-creating it as I posted. I found that there is a generic EventHandler<TEventArgs>, so you don't need to create the generic delegate, but you still need the generic EventArgs<T> class, because TEventArgs: EventArgs.
Another EDIT: One downside (to me) of the built-in solution is the extra verbosity:

public event EventHandler<EventArgs<Foo>> FooChanged;


public event EventHandler<Foo> FooChanged;

It can be a pain for clients to register for your events though, because the System namespace is imported by default, so they have to manually seek out your namespace, even with a fancy tool like Resharper... Anyone have any ideas pertaining to that?

No, I don't think this is the wrong approach. I think it's even recommended in the [fantastic] book Framework Design Guidelines. I do the same thing.

I see little functional difference between using a property

public readonly property foo as string
    return bar
  end get
end property

or a function

public function foo() as string
  return bar
end function

Why would I want to use one form over the other?


If you are basing yourself upon the Framework Design Guidelines, you must be using a method only when you are actually performing an action or accessing resouces that could be expensive to use(database, network).

The property give the user the impression that the values are stored in memory and that reading a property is fast while calling a method might have further implication than just "get the value".

Brad Abrams actually wrote an article about it and is even posted on MSDN here.

I would highly suggest that you buy the book Framework Design Guidelines. It's a must read for every developer.

The Close method on an ICommunicationObject can throw two types of exceptions as MSDN outlines here. I understand why the Close method can throw those exceptions, but what I don't understand is why the Dispose method on a service proxy calls the Close method without a try around it. Isn't your Dispose method the one place where you want make sure you don't throw any exceptions?

It seems to be a common design pattern in .NET code. Here is a citation from Framework design guidelines

Consider providing method Close(), in addition to the Dispose(), if close is standard terminology in the area. When doing so, it is important that you make the Close implementation identical to Dispose ...

Here is a blog post in which you can find workaround for this System.ServiceModel.ClientBase design problem

Is there any relevance of a 'public' constructor in an abstract class? I can not think of any possible way to use it, in that case shouldn't it be treated as error by compiler (C#, not sure if other languages allow that).

Sample Code:

internal abstract class Vehicle
    public Vehicle()

The C# compiler allows this code to compile, while there is no way i can call this contructor from the outside world. It can be called from derived classes only. So shouldn't it allow 'protected' and 'private' modifiers only. Please comment.

Dupe: there is another question on SO just like this: Abstract class constructor access modifier

The answers on that question come down to the same thing in the end: it does not really matter if you declare it protected or public.

Also there seems to be some discussion about it in literature (e.g. in Framework Design Guidelines). This is referenced in this blogpost: Good design or bad design of abstract class?

I am writing an .NET wrapper API for the Netflix API.

At this point I can choose to represent URLs as either strings or URI objects. Seems to me there is a good case for both.

So if you were using an API, which would you prefer?

The below quote is from: Framework Design Guildelines
I highly recommend this book to anyone developing frameworks on .Net

Do use System.Uri to represent URI / URL data.
(For Parameters, properties, and return values)

System.Uri is a much safer and richer way of representing URIs. Extensive manipulation of URI-related data using plain strings has been shown to cause many security and correctness problems.

Consider providing string-based overloads for most commonly used members with System.Uri parameters.

In cases where the usage pattern of taking a string from a user will be common enough, you should consider adding a convenience overload accepting a string. The string-based overload should be implemented in terms of the Uri-based overload.

Do Not automatically overload all Uri-based members with a version that accepts a string.

Generally, Uri-based APIs are preferred. String-based overloads are meant to be helpers for the most common scenarios. Therefore, you should not automatically provide string-based overloads for all variants of the Uri-based members. Be selective and provide such helpers just for the most commonly used variants.

EDIT (per comments): The book specifically states: "Extensive manipulation of URI-related data using plain strings has been shown to cause many security and correctness problems." I am not sure what additional justification you want for using System.Uri / UriBuilder. Additionally, why wouldn't you want to take advantage of the framework to read/manipulate a URI?

When designing an API that will be used by others it is important to make them approachable, as well as reliable. For this reason the book does mention, you should provide "nice" overloads for common functionality. However, to ensure correctness, you should always implement the underlying code with URIs.

Can you please clarify your wants, or reasons to use only strings?

We currently have a heated internal debate as to whether the actual .NET assembly name should include the code's version number (e.g. CodeName02.exe or CompanyName.CodeName02.dll). Does anyone know of an authoritative source, like Microsoft, that provides guidance on this issue?

Framework Design Guidelines by Krzysztof Cwalina and Brad Abrams of Microsoft suggests assembly naming like


I further support this (NOT using version #) because the GAC and dll file properties will show the version.

I'm faced with writing a framework to simplify working with a large and complex object library (ArcObjects). What guidelines would you suggest for creating a framework of this kind? Are static methods preferred? How do you handle things like logging? How do you future proof your framework code from changes that a vendor might introduce?

I think of all of the various wrappers and helpers I've seen for NHibernate, log4net, and code I've read from projects like NLog and NetTopologySuite and I see so many good approaches, but honestly I'm at a loss where to start.

BTW - I'm working in C# 3.5 but it's more about recommended approach rather than language.

Brad Abrams' Framework Design Guidelines book is all about this. Might be worth a look.

My background is primarily as a Java Developer, but lately I have been doing some work in .NET. So I have been trying to do some simple projects at home to get better at working with .NET. I have been able to transfer much of my Java experience into working with .NET (specifically C#), but the only thing that has really perplexed me is namespaces.

I know namespaces are similar to Java packages, but as from what I can tell the main difference is that with Java packages they use actual file folders to show the seperation, while in .NET it does not and all the files reside in a single folder and the namespace is simply declared in each class.

I find this odd, because I always saw packages as a way to organize and group related code, making it easier to navigate and comprehend. Since in .NET it does not work this work this way, overtime, the project appears more overcrowded and not as easy to navigate.

Am I missing something here? I have to be. Should I be breaking things into separate projects within the solution? Or is there a better way to keep the classes and files organized within a project?

Edit: As Blair pointed out this is pretty much the same question asked here.

Yep, in .NET namespace doesn't depend on file system or anything else. It's a great advantage in my opinion. For example you can split your code across different assemblies which allows flexible distribution.

When working in Visual Studio, IDE tends to introduce new namespace when you add new folder to project tree.

Here is a useful link from MSDN:

Namespace Naming Guidelines

The general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design as follows.

Of course you can use namespaces in the way you find more suitable. However if you going to share your code, I would recommend to go along with accepted standards.


I highly recommend to any .net developer to get a copy of Framework design guidelines This book will help you to understand how and why .NET is designed.

I'm writing a c# application which uses automation to control another program. Naturally that program must be running for my program to work. When my program looks for the application and can't find it I'd like to throw an exception (for now later of course I could try opening the application, or telling the user to open it, or ...).

Should I implement a custom exception - or use the existing NotSupportedException (or one of the other .NET exceptions). If a custom exception, what would you suggest? I was thinking of implementing a custom exception I'd call it MyAppNameException and then just use the message to declare what the problem was?

Are there any general rules to throwing exceptions in a way that makes your program more readable and user friendly, or am I just giving this too much thought :)?


The Framework Guidelines book that I use indicates that you should only create a custom exception when the error condition can be programmatically handled in a different way than any existing exceptions.

In your case, if you wanted to create a custom exception in order to launch a back-end installation program, that is unique and I think a custom exception would be okay.

Otherwise, something from the System.Runtime.InteropServices.ExternalException heirarchy may be appropriate.

Just thought I'd see if somebody could explain why Anders decided that this is valid...

   //single statement
   ///single statement

but this is not...

   //single statement
   //single statement

To quote from Framework Design Guidelines in the section about "General Style Conventions" this is said about braces:

AVOID omitting braces, even if the language allows it. Braces should not be considered optional. Even for single statement blocks, you should use braces. This increase code readability and maintainability.

There are very limited cases when omitting braces might be acceptable, such as when adding a new statement after an existing singöe-line statement is either impossible or extremely rare. For example, it is meaningless to add a statement after a throw statement:

if(someExpression) throw new ArgumentOutOfRangeExcetion(...);

Another exception to the rule is braces in case statements. These braces can be omitted as the caseand breakstatements indicate the begining and the start of the block.

What Anders thinks is subjective and argumentative, this is the recommendation.

You might also want to look at the section about bracing in the coding convention over at msdn.

As a beginning programmer, I'm trying to settle on a standard naming convention for myself. I realize that it's personal preference, but I was trying to get some ideas from some of you (well a LOT of you) who are much smarter than myself.

I'm not talking about camel notation but rather how do you name your variables, etc. IMHO, var_Quantity is much more descriptive than Q or varQ. However, how do you keep the variable from becoming too long. I've tried to be more descriptive with naming my controls, but I've ended up with some like "rtxtboxAddrLine1" for a RadTextBox that holds address line 1. Too me,that is unmanageable, although it's pretty clear what that control is.

I'm just curious if you have some guides that you follow or am I left up to my own devices?

For .NET API design (and some general C# guidelines) check Krzysztof Cwalina and Brad Abrams' Framework Design Guidelines

Regards, tamberg

I am looking for web sites or books that would help a C++ developer to pick up C#. So far, this is the best one I've found.

Frankly, when I learned .NET, it was difficult to understand it in many ways from a C++ background. I found that trying to fit C# into a C++ mindset actually worked against me - not for me.

I wouldn't focus on trying to find something that's C# for C++ developers - try to just find good resources for C# in general. Good, detail C# and .NET framework books will get you there, and your C++ background will just help you understand the details a bit better. Learning C# will be about learning the frameworks, the expected manner of doing things, and forgetting a lot of C++ habits.

I would recommend a couple of detailed books that aren't focused on beginner topics, such as CLR via C# and C# in Depth.

I also think that the Framework Design Guidelines was probably the most valuable resources for getting me to think in C#/.NET instead of C++ - it really goes into why the framework is the way it is, and learning how to write code that other C# developers will want to maintain. The guidelines are available online, but the book is very helpful in that it also explains the reasons behind the guidelines, not just the "rules."

I find Peter Sestoft's Java Precisely to be a nice concise reference to Java for C++ programmers; he also is the author of C# Precisely which is written in the same spirit, though I haven't read it so I can't speak to it.

I have created a Windows Forms application in .NET 2 using C# that runs continuously. For most accounts I am pleased with it, but it has been reported to me that it has failed occasionally. I am able to monitor its performance for 50% of the time and I have never noticed a failure.

At this point I am concerned that perhaps the program is using too many resources and is not disposing of resources when they are no longer required.

What are the best practices for properly disposing created objects that have created timers and graphical objects like graphics paths, SQL connections, etc. or can I rely on the dispose method to take care of all garbage collection?

Also: Is there a way that I could monitor resources used by the application?

There are a few ways of ensuring this. The main help I find is by utilising the "using" keyword. This is applied as such:

using(SqlConnection connection = new SqlConnection(myConnectionString))
    /* utilise the connection here */ 

This basically translates into:

SqlConnection connection = null;
    connection = new SqlConnection(myConnectionString);
    if(connection != null) connection.Dispose();

As such it only works with types that implement IDisposable.

This keyword is massively useful when dealing with GDI objects such as pens and brushes. However there are scenarios where you will want to hold onto resources for a longer period of time than just the current scope of a method. As a rule it's best to avoid this if possible but for example when dealing with SqlCe it's more performant to keep one connection to the db continuously open. Therefore one can't escape this need.

In this scenario you can't use the "using" but you still want to be able to easily reclaim the resources held by the connection. There are two mechanisms that you can use to get these resources back.

One is via a finaliser. All managed objects that are out of scope are eventually collected by the garbage collector. If you have defined a finaliser then the GC will call this when collecting the object.

public class MyClassThatHoldsResources
    private Brush myBrush;

    // this is a finaliser
       if(myBrush != null) myBrush.Dispose();

However the above code is unfortunately crap. The reason is because at finalizing time you cannot guarantee which managed objects have been collected already and which have not. Ergo the "myBrush" in the above example may have already been discarded by the garbage collector. Therefore it isn't best to use a finaliser to collect managed objects, its use is to tidy up unmanaged resources.

Another issue with the finaliser is that it is not deterministic. Lets say for example I have a class that communicates via a serial port. Only one connection to a serial port can be open at one time. Therefore if I have the following class:

class MySerialPortAccessor
    private SerialPort m_Port;

    public MySerialPortAccessor(string port)
        m_Port = new SerialPort(port);

        if(m_Port != null) m_Port.Dispose();

Then if I used the object like this:

public static void Main()

private static void Test1()
    MySerialPortAccessor port = new MySerialPortAccessor("COM1:");
    // do stuff

private static void Test2()
    MySerialPortAccessor port = new MySerialPortAccessor("COM1:");
    // do stuff

I would have a problem. The issue is that the finaliser is not deterministic. That is to say I cannot guarantee when it will run and therefore get round to disposing my serial port object. Therefore when I run test 2 I might find that the port is still open. While I could call GC.Collect() between Test1() and Test2() which would solve this problem it isn't recommended. If you want to get the best performance out of the collector then let it do its own thing.

Therefore what I really want to do is this:

class MySerialPortAccessor : IDispable
    private SerialPort m_Port;

    public MySerialPortAccessor(string port)
        m_Port = new SerialPort(port);

    public void Dispose()
        if(m_Port != null) m_Port.Dispose();

And i'll rewrite my test like this:

public static void Main()

private static void Test1()
    using( MySerialPortAccessor port = new MySerialPortAccessor("COM1:"))
        // do stuff

private static void Test2()
    using( MySerialPortAccessor port = new MySerialPortAccessor("COM1:"))
        // do stuff

This will now work. So what of the finaliser? Why use it?

Unmanaged resources and possible implementations that don't call Dispose.

As the writer of a component library that others use; their code may forget to dispose of the object. It's possible that something else might kill the process and hence the .Dispose() would not occur. Due to these scenarios a finaliser should be implemented to clean any unmanaged resource as a "worst case" scenario but Dispose should also tidy these resources so you have your "deterministic clean up" routine.

So in closing, the pattern recommended in the .NET Framework Guidelines book is to implement both as follows:

public void SomeResourceHoggingClass, IDisposable

    public void Dispose()

    // virtual so a sub class can override it and add its own stuff
    protected virtual void Dispose(bool deterministicDispose)
         // we can tidy managed objects


         // if we've been disposed by .Dispose()
         // then we can tell the GC that it doesn't
         // need to finalise this object (which saves it some time)

Basically, the question is: Do the Exceptions in C# affect the performance a lot? Is it better to avoid Exceptions rethrow? If i generate an exception in my code, does it affect a performance?

Sorry for the sillines of the question itself

Microsoft's Design Guidelines for Developing Class Libraries is a very valuable resource. Here is a relevant article:

Exceptions and Performance

I would also recommend the Framework Design Guidelines book from Microsoft Press. It has a lot of the information from the Design Guidelines link, but it is annotated by people with MS, and Anders Hejlsberg, himself. It gives a lot of insight into the "why" and "how" of the way things are.

I guess I need to create an Assembly but how do I do this concretely when I have multiple classes ? There seems to be many steps involved and searching on the net I cannot find any article on this subject. Can anyone point me to one if it exists ?

Sometimes I've made a namespace in C# (I don't know if the problem is the same in VB.NET) containing 'System' and when I include it from a different DLL it goes crazy and conflicts with everything containing 'System'. This leads to crazy errors such as the following :

The type or namespace name 'ServiceModel' does not exist in the namespace 'RR.System'

The type or namespace name 'Runtime' does not exist in the namespace 'RR.System'

The type or namespace name 'SerializableAttribute' does not exist in the namespace 'RR.System'

If you don't know what I'm talking about then good for you :) I'm sure many have seen this issue.

I'm not completely sure why it does this. It will occur even in files, such as generated code for web services that doesn't contain any reference to RR.System.

This all occurs just because I'm including RR.System the DLL in a different project.

How can I avoid this happening? Or fix it?

If your project contains references to both System and your custom library (RR.System), the compiler will have an ambiguous reference to sort out. It's not sure which one you want.

You can always use aliasing to ensure that your code is explicitly referencing the correct code from your project.

BTW, there's a huge amount of best practice information to follow from Brad Abrams in Framework Design Guidelines.

Why wouldn't I choose abstract? What are the limitations to declaring a class member virtual? Can only methods be declared virtual?

You question is more related to style than technicalities. I think that this book has great discussion around your question and lots of others.

I have this class:

class DoSomething
    private int timesDone;

Which is the right way to named variable 'timesDone'?

Sometimes I see named as m_timesDone. Is this correct? Where I can find information about naming guidelines?

Thank you!

According to MS standards your code is OK. Having prefixes as m_ is not really necessary when you have advanced IDE. However short prefix like _ can be used to take advantage of auto complete feature to quickly sort out class members.

I would recommend you to get a copy of "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book to learn more on MS standards

In order to to get the number of subitems in dotnet sometimes i have to ask a property Lenght sometimes i have to ask a property Count.

Is there any reason for the distinction?


   int[] a; if (a.Length == 0) ....
   IList<int> b; if (b.Count == 0) ....

Note Difference between IEnumerable Count() and Length sounds similar but does not answer the semantic between Length and Count

I can remember the Framework Design Guidelines contains an annotation about this difference (I will at a qoute of it tomorrow). What I recall is that the designers think this is a quirk in the design, because it doesn't make sense for a lot of developers. Remember that in the beginning there were no design guidelines for .NET and much of the .NET API was copied from Java, including the quirks.

Sure, there's a type of project in Visual Studio that outputs a DLL that people can use. I know that. I'm just wondering what are some of the standards that devs will expect when using my DLL file.

I'll be providing a class that searches for movies in IMDB and returns results for a dev to consume.

Not a webservice, but a local DLL file. (I'm aware that IMDB frowns upon web scraping, but I'm also aware that they give permission to people if asked. My permission is already sent.)

How should I approach this?

If you, or anybody, is serious about creating a good framework for others to use, check out

We are developing a middleware SDK, both in C++ and Java to be used as a library/DLL by, for example, game developers, animation software developers, Avatar developers to enhance their products.

What I would like to know is this: Are there standard "Best Practices" for the development of these types of API?

I am thinking in terms of useability, readability, efficiency etc.

There are lots of ways to design apis, depending on what you are solving. I think a full answer to this question would be worthy off a whole book, such as the gang of four patterns book. For Java specifically, and also just OO programming in general, I would recommend Effecitve Java 2nd Edition. The first is general and alot of popular programming patterns, when they apply and their benefits. Effective Java is Java centered, but parts of it is general enough to apply to any programming language.

Take a look at Framework Design Guidelines. I know it is .NET specific, but you can probably learn a lot of general information from it too.

Which of the following three options would you choose for a property name in C#, and why?

  1. YearToDateWages
  2. YTDWages
  3. YtdWages

It depends.

If you are making a library that will see external use, the .NET Framework Design Guidelines say that #1 is preferred.

If it's an internal application/library, then I recommend using the format that is consistent with your teams development standard.

Have read through the MSDN naming guidelines and could not find a clear answer, other than that you should try to avoid underscores in general. Let's say I have the following:

public class Employee
    private string m_name;  //to store property value called Name

    public string Name
        get { return m_name; }
        set { m_name = value; }

    public void ConvertNameToUpper()
        //by convention should you use this
        return m_name.ToUpper();

        //or this
        return Name.ToUpper(); 

What is the proper naming convention for m_name in the above? For example, in code I inherit I commonly see:

  • m_name
  • _name
  • name
  • myName or some other random identifier

Which one (or another) is most commonly accepted?

As a follow-up, in the methods of the class, do you refer to the internal (private) identifier or to the public property accessor?

The framework Design guidelines book says that you shouldn't prefix your variables with _ - you should just use a lower case for the name of the variable, and Code Complete 2nd edition I believe says you shouldn't prefix your variables with m_.

Here's the setup I have in a vs2008 solution:

Data layer in a project named MyProject.Data

Web application in a project named MyProject.Web

MyProject.Web has a reference to MyProject.Data

In MyProject.Web I have a class I use called "MySite.Utils"

I want to be able to use MySite.Utils in MyProject.Data but I can't because it would cause a circular reference.

One solution which is NOT possible is creating a third project and moving "MySite.Utils" in there because MySite.Utils actually uses MyProject.Data (thus it needs to reference it and another circular reference would be created)

What's the best/easiest way to fix this?

Sounds like you could benefit (and enjoy!) from reading this...

Most of the time during coding, i found that whether i can write code in less number of line.

I don't know when we write some login in less number of line in c# then whether we achive good performance or not? whether dotnet compiler compile code faster or not?

Is there any source of tutorial/ book/ guideline so that we will make checklist before writing code.

You asked for a book or article. One of the best books for best practices in .NET is

The book is written by members of the .NET development team themselves.

"less number of line"? This is not so relevant. Computing n'th Fibonacci number can be implemented recursively with exponential complexity or by using matrix multiplication in logarithmic time, with more lines of code. Kolmogorov complexity is not always to be minimized.

Look a rule: avoid unnecessary boxing, as in:

int x=3; Console.WriteLine("x ={0}", x); //wrong; but: Console.WriteLine("x ={0}", x.ToString());

I always regarded the book Effective C#: 50 Specific Ways to Improve Your C# as a good book showing you how to write better code in C#; for example, it explains why you should use foreach instead of for when iterating over a collection.

public struct Cache {
    public int babyGangters { get; set; }
    public int punks { get; set; }
    public int ogs { get; set; }
    public int mercs { get; set; }
    public int hsPushers { get; set; }
    public int collegeDealers { get; set; }
    public int drugLords { get; set; }
    public int streetHoes { get; set; }
    public int webcamGrls { get; set; }
    public int escort { get; set; }
    public int turns { get; set; }
    public int cash { get; set; }
    public int bank { get; set; }
    public int drugs { get; set; }
    public int totalValue { get; set; }
    public int attackIns { get; set; }
    public int attackOuts { get; set; }
    public int status { get; set; }
    public int location { get; set; }

The rule of thumb is that a struct should not be bigger than 16 bytes (according to the Framework Design Guidelines). Your struct is 76 bytes (= 19 * 4), so it is pretty big. However, you will have to measure the performance. Big structs can be beneficial for some applications.

The Framework Design Guidelines state:

Avoid defining a struct unless the type [...] an instance size under 16 bytes.

One of the annotations from Jeffrey Richterto this guidlines state:

Value types can be more than 16 bytes if you don't intend to pass them to other methods or copy them to and from a collection class (like an array).

Silly question really but just was wondering about other peoples naming conventions for DAL and BLL if there were any better names for them than those ones.

I guess you mean the projects you are creating.

If you follow ".NET Framework design guidelines"

  • Avoid such abbreviations

I usually see something like this:



However one might argue where to put the logic or even if you should name it Logic or BLL at all. It depends on the system in wide, if you are creating a Banking system you might not want to put all logic in a Logic namespace but you might want to split it up into more spaces like:



Where these layers have their own set of logic layers.

What are the most common naming conventions in C# for classes, namespaces and methods? Is it common to have getter/setter style methods as in Java?

No it is not common to use getter /setter style names in C#. Properties should be used for almost all places you would use a getter / setter in Java.

IMHO, the defacto standard for naming conventions comes from the Framework Design Guidelines. It's enforced by several tools (FxCop) and is the dominant style of many libraries including the BCL.

According to Martin Fowler "Something can be public but that does not mean you have published it." Does this mean something like this:

public interface IRollsRoyceEngine
    void Start();
    void Stop();
    String GenerateEngineReport();

public class RollsRoyceEngine : IRollsRoyceEngine
    public bool EngineHasStarted { get; internal set; }

    public bool EngineIsServiceable { get; internal set; }

    #region Implementation of IRollsRoyceEngine

    public void Start()
        if (EngineCanBeStarted())
            EngineHasStarted = true;
            throw new InvalidOperationException("Engine can not be started at this time!");

    public void Stop()
        if (EngineCanBeStopped())
            EngineHasStarted = false;
            throw new InvalidOperationException("Engine can not be started at this time!");

    public string GenerateEngineReport()
        return EngineIsServiceable ? "Engine is fine for now" : "Hmm...there may be some problem with the engine";


    #region Non published methods

    public bool EngineCanBeStarted()
        return EngineIsServiceable ? true : false;

    public bool EngineCanBeStopped()
        return EngineIsServiceable ? true : false;

    public void CheckEngineStatus()
        EngineIsServiceable = true;
        //_EngineStatus = false;



Can it be said that published interface of this is IRollsRoyceEngine not whatever is in RollsRoyceEngine?

If so what is the real difference between public and published methods?

In my opinion mentioned white paper talks about target audience of the API rather than the distinction between interface and its implementation.

You can find analogy in Framework Design Guidelines which says that once your API shipped you have a contract with consumers. For example, if you shipped in v1 of your framework IService interface you cannot change it in v2 because it will introduce breaking changes to end developers. Instead you must create new interface IService2 inhereted from IService and ship it with v2.

So basically public API becomes published once you "sign a contract" with end developers.

Returning back to your code - it will be published when you ship it to development community for example.

Hope this explanation will help.

Socket.Dispose() is an inaccessible member. However, we can bypass this by doing the following:


Two questions:

  1. Why is this allowed?
  2. How does this work internally?

Whenever a class implements a method such as Close() which accomplishes the same work as Dispose(), then it is recommended to explicitly implement the IDisposable interface, so that a developer will typically only see the Close() method, yet the Dispose method is still accessible through the IDisposable interface for use by the framework where a Dispose method is expected.

Sometimes it makes sense to essentially expose Dispose under a different name, such as Close, where it makes for more readable code. You see these throughout the .NET Framework with things that can be "Closed" such as file handles and connections.

Edit: See

I had a little discussion with a friend about the usage of collections in return/input values of a method. He told me that we have to use - the most derived type for return values. - the least derived type for input parameters.

So, it means that, for example, a method has to get a ReadOnlyCollection as parameter, and as return a List.

Moreover, he said that we must not use List or Dictionary in publics API, and that we have to use, instead Collection, ReadOnlyCollection, ... So, in the case where a method is public, its parameters and its return values must be Collection, ReadOnlyCollection, ...

Is it right ?

Maybe your friend read: Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries

It is a great book, and it covers questions like this in detail.

I have a simple solution with the following projects as follows (base namespaces match the project name)...


I'm just trying to find a better name for BusinessLayer, I just don't really like it for some reason. So my question is what do you call your BusinessLayer projects/namespaces.

article on namespace guidelines

I've seen BusinessLogic, but it as noted by the rest of the answers here a lot of time you will see...

  • MyCompany.MyProduct.DataAccessLayer (or DAL)
  • MyCompany.MyProduct.BusinessEntities (or BusinessObjects)
  • MyCompany.MyProduct.BusinessLogic
  • MyCompany.MyProduct.Web.Service
  • MyCompany.MyProduct.Web.Site

Another good reference for this type of stuff is the Framework Design Guidelines book.

I'm writing unit tests for classes which have properties that have setters but no getters.

I want to be able to test these setters to make sure they are setting the data correctly.

I find my options are:

  • write getters for these functions so that I can test if they are set correctly
  • write a method such as testAllSetters() which test them all at once

But both solutions are undesirable since it adds unneeded functionality to the class just for the sake of testing it.

  • I could also test the output of the class to see that it is correct in general, but in many cases this doesn't test the individual setters as I would like

What is the best way to unit test setters on classes that do not have paired getters?

The problem here is that your don't want to change your API for your unit tests. Start looking at your unit tests as another user/consumer of your API. Just like developers using that library, unit tests have their own set of requirements. When you see your unit tests as consumer of your API, there will be a user that uses those getters, and it will justify them.

When this is not possible to change your API (for instance if you're developing an reusable framework), make the unit testing API internal and use the InternalsVisibleToAttribute to allow your testing library to access internal methods of your code.

Leaving unit tests aside, you still might want to consider having getters on those properties, because having properties without getters is very unintuitive for developers. The Framework Design Guidelines even have a rule against this:

DO NOT provide set-only properties or properties with the setter having broader accessibility than the getter.

You might also want to take that into consideration.

Good luck.

Please bare with my I'm very new to programming.

I'm working through a tutorial of C# at the moment. And so far all variables and helper methods that I've created are capitalizedLikeThis. I've been doing this all in the Progam class.

Today I've created my first new class and within it a method, and the way the method was written WasLikeThis with the first letter also capitalized, there was no explanation to this. Is it just a common convention? And if so, is there a specific reason for it?


Yes there is a reason for it. It is a Pascal Case naming convention for method names that is a standard in the .NET framework.

All the types in the framework class library (FCL) follow the mentioned naming convention, and when you create some custom types or add methods to existing types you are augmenting the capabilites of the framework for your specific application needs.

Your method capitalizedLikeThis is part of the Program class, which has an API that follows the .NET naming conventions. For example it contains a ToString() instance method so you could do:

var program = new Program();

So the real question is do you want to add a method to the Program class that breaks the naming convention of the existing API? Consistency is a good thing and that is why you should follow the convention.

If you want more information on this topic you can check out the only relevant book for .NET design guidelines containing naming conventions, and many other details related to the .NET framework design decisions:

Or read the reduced MSDN article based on the book:

Sometimes I dont know witch type of exception should I throw. So I usually throw Exception(). Is there some nice article about this?

The problem with throwing a generic exception is that it restricts the ability of your code further up the stack to handle it properly (i.e. best practice is to trap the most specific exception possible before falling back, and to only capture what you can handle).

Jeffrey Richter has an excellent section on exception handling (including info on the System.Exception namespace) in CLR via C#

"Framework Design Guidelines" by Cwalina and Abrahms covers this topic really well (IMHO).

It is available for free online here, or the book (not free) here (UK) or here(US). Look in the section entitled Design Guidelines for Exceptions.

Which one should you use when you want to set the state of a Windows Forms control:

  1. Setting a Windows Forms state using a public property?

  2. Setting a Windows Forms state using an overloaded constructor that accepts a parameter?

They're exactly the same. Or at least they should be, according to the Framework Design Guidelines. So you can expect that any of the standard classes exposed by the .NET Framework behave this way.

Any constructor method that accepts a parameter corresponding to a property should do nothing more than set that property to the specified value.

Quoting from Framework Design Guidelines by Cwalina and Abrams:

Do use constructor parameters as shortcuts for setting main properties.

There should be no difference in semantics between using the empty constructor followed by some property sets, and using a constructor with multiple arguments. The following three code samples are equivalent:

EventLog applicationLog = new EventLog();
applicationLog.MachineName = "BillingServer";
applicationLog.Log = "Application";

EventLog applicationLog = new EventLog("Application");
applicationLog.MachineName = "BillingServer";

EventLog applicationLog = new EventLog("Application", "BillingServer");

Similar guidelines concerning constructors are also available online from MSDN here.

Are the naming conventions similar in different languages? If not, what are the differences?

Of course there are some common guidelines but there are also differences due to difference in language syntax\design.

For .NET (C#, VB, etc) I would recommend following resource:


One of the best recommendations I can make is to read the relevant section(s) of Steve McConnell's Code Complete (Amazon Link). He has an excellent discussion on naming techniques.




I'm a bit bewildered on this subject, as I relate variable prefixes to being a thing of the past now, but with Visual Studio 2010 onwards (I'm currently using 2012), do people still do this and why?

I only ask because, these days, you can hover over any variable and it'll tell you the variable type and scope. There's literally no requirement for pre-fixing being there for readability.

By this I mean:

string strHello
int intHello


And I'm being language/tool biased here - as Visual Studio takes a lot of the legwork out for you in terms of seeing exactly what type the variable is, including after conversions in the code. This is not a "general programming" question.

The significant point is that the variable name "should not" represent its type. Instead, It should indicate the "business semantic" of the variable; The type of the variable is subject to change during the code maintenance, but the semantics of that variable is rarely changed.

Incorporating "StyleCop" into your development lifecycle can enforce consistent code style amongst team members.

UPDATE: This excerpt from the Chapter 3 of "Framework Design Guidelines" which is dedicated to "Naming Guidelines" helps to clarify the issue:

Identifier names should clearly state what each member does and what each type and parameter represents. To this end, it is more important that name be clear than that it be short. Names should correspond to scenarios , logical or physical parts of the system, and well-known concepts rather than to technologies or architecture.

DO choose easily readable identifier names.[...]

DO favor readability over brevity.[...]

DO NOT use underscores, hyphens, or any other non-alphanumeric characters.[...]

DO NOT use Hungrian Notation. [...]

I sometimes use

if (this._currentToolForeColor.HasValue)
    return this._currentToolForeColor.Value;
    throw new InvalidOperationException();

other times I use

if (this._currentToolForeColor.HasValue)
    return this._currentToolForeColor.Value;
throw new InvalidOperationException();

The two are equivalent, I know, but I am not sure which is the best and why.

This goes even further as you can use other execution-control statements such as brake or continue :




EDIT 1 : Yes the loop example(s) suck because they are synthetic (i.e.: made up for this question) unlike the first which is practical.

For a better and cleaner code, I think it is better to choose always this form:

   //do stuff
   //do stuff

..and so on.

It's just a matter of "taste", but even if you have more rows of code, this is clearly readable, because you don't have to interpret nor understand, you can follow the code flow with your finger easily. So, for me, always the else even if a return prevents fallback into following code, always brackets event if you have a one-row if/else and so on.

As far as I can remember, this is also suggested in Framework Design Guidelines, very easy book with lot of "do this" and "don't do this" guidelines.