Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition)

Author: Krzysztof Cwalina, Brad Abrams
All Stack Overflow 104
This Year Stack Overflow 3
This Month Stack Overflow 1


by anonymous   2019-01-13

It is considered a best practice to NEVER return null when returning a collection or enumerable. "ALWAYS" return an empty enumerable/collection. It prevents the aforementioned nonsense, and prevents your car getting egged by co-workers and users of your classes.

In general that's correct, but there are cases when returning null isn't wrong. so the "ALWAYS" has to be omitted.

Also, a great source is the Framework Design Guidelines 2nd Edition (pg. 256):

DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead.

by anonymous   2018-03-19

Simple Injector does not contain an IContainer abstraction, because that would be useless:

  • It would be useless for Simple Injector to define it, because your code would in that case still depend on the library (since Simple Injector defines that abstraction), and this causes a vendor lock-in, which Simple Injector tries to prevent.

  • Any code you write, apart from the application's Composition Root, should not depend on the container, nor on an abstraction over the container. Both are implementations of the Service Locator anti-pattern.

  • You should NOT use a DI library when unit testing. When unit testing, you should manually inject all fake or mock objects in the class under test. Using a container only complicates things. Perhaps you are using a container, because manually creating those classes is too cumbersome for you. This might indicate problems with your code (you might be violating the Single Responsibility Principle) or your tests (you might be missing a factory method to create the class under test).

  • You might use the container for your integration tests, but you shouldn't have that many integration tests in the first place. The focus should be on unit tests and this should be easy when applying the dependency injection pattern. On top of that, there are better ways of hiding the container from your integration tests, compared to depending on a very wide library-defined interface.

  • It is trivial to define such interface (plus an adapter) yourself, which justifies not having it in the library. It is your job as application developer to define the right abstractions for your application as stated by the Dependency Inversion Principle. Libraries and frameworks that tend to do this will fail most of the time in providing an abstraction that works for everyone.

  • The library itself does not use that abstraction and a library should, according to the Framework Design Guidelines, in that case not define such abstraction for you. As stated in the previous point, Simple Injector would get the abstraction wrong anyway.

  • Last but not least, the Simple Injector container does actually implement System.IServiceProvider which is defined in mscorlib.dll and can be used for retrieving service objects.

by anonymous   2018-03-19

From the Framework Design Guidelines 2nd Edition (pg. 256):

DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead.

Here's another interesting article on the benefits of not returning nulls (I was trying to find something on Brad Abram's blog, and he linked to the article).

Edit- as Eric Lippert has now commented to the original question, I'd also like to link to his excellent article.

by anonymous   2017-11-20
@Amy just to be sure, that one
by anonymous   2017-10-01
There are many classes in the BCL that either violated both LSP and ISP. This is the hard part of designing a reusable class library that has to be used for so many different use cases, while trying to keep the API intuitive to work with. There are more factors at play here than simply the SOLID principles. The [Framework Design Guidelines]( give some great clues about this.
by anonymous   2017-08-20

After spending 10 minutes editing the question for formatting, I'm still going to downvote it. There's no way I'm going to read all that.

Go pick up a copy of

Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition)

by anonymous   2017-08-20

You don't need a list of 'bad' exceptions, you should treat everything as bad by default. Only catch what you can handle and recover from. CLR can notify you of unhandled exceptions so that you can log them appropriately. Swallowing everything but a black listed exceptions is not a proper way to fix your bugs. That would just mask them. Read this and this.

Do not exclude any special exceptions when catching for the purpose of transferring exceptions.

Instead of creating lists of special exceptions in your catch clauses, you should catch only those exceptions that you can legitimately handle. Exceptions that you cannot handle should not be treated as special cases in non-specific exception handlers. The following code example demonstrates incorrectly testing for special exceptions for the purposes of re-throwing them.

public class BadExceptionHandlingExample2 {
    public void DoWork() {
        // Do some work that might throw exceptions.
    public void MethodWithBadHandler() {
        try {
        } catch (Exception e) {
            if (e is StackOverflowException ||
                e is OutOfMemoryException)
            // Handle the exception and
            // continue executing.

Few other rules:

Avoid handling errors by catching non-specific exceptions, such as System.Exception, System.SystemException, and so on, in application code. There are cases when handling errors in applications is acceptable, but such cases are rare.

An application should not handle exceptions that can result in an unexpected or exploitable state. If you cannot predict all possible causes of an exception and ensure that malicious code cannot exploit the resulting application state, you should allow the application to terminate instead of handling the exception.

Consider catching specific exceptions when you understand why it will be thrown in a given context.

You should catch only those exceptions that you can recover from. For example, a FileNotFoundException that results from an attempt to open a non-existent file can be handled by an application because it can communicate the problem to the user and allow the user to specify a different file name or create the file. A request to open a file that generates an ExecutionEngineException should not be handled because the underlying cause of the exception cannot be known with any degree of certainty, and the application cannot ensure that it is safe to continue executing.

Eric Lippert classifies all exceptions into 4 groups: Fatal, 'Boneheaded', Vexing, Exogenous. Following is my interpretation of Eric's advice:

  Exc. type | What to do                          | Example
Fatal       | nothing, let CLR handle it          | OutOfMemoryException
Boneheaded  | fix the bug that caused exception   | ArgumentNullException
Vexing      | fix the bug that caused exception   | FormatException from 
            | (by catching exception  because     | Guid constructor
            | the framework provides no other way | (fixed in .NET 4.0 
            | way of handling). Open MS Connect   | by Guid.TryParse)
            | issue.                              | 
Exogenous   | handle exception programmatically   | FileNotFoundException 

This is roughly equivalent to Microsoft's categorization: Usage, Program error and System failure. You can also use static analysis tools like FxCop to enforce some of these rules.

by anonymous   2017-08-20

Generally, the rule goes something like this:

  • Inheritance describes an is-a relationship.
  • Implementing an interface describes a can-do relationship.

To put this in somewhat more concrete terms, let's look at an example. The System.Drawing.Bitmap class is-an image (and as such, it inherits from the Image class), but it also can-do disposing, so it implements the IDisposable interface. It also can-do serialization, so it implements from the ISerializable interface.

But more practically, interfaces are often used to simulate multiple inheritance in C#. If your Processor class needs to inherit from something like System.ComponentModel.Component, then you have little choice but to implement an IProcessor interface.

The fact is that both interfaces and abstract base class provide a contract specifying what a particular class can do. It's a common myth that interfaces are necessary to declare this contract, but that's not correct. The biggest advantage to my mind is that abstract base classes allow you provide default functionality for the subclasses. But if there is no default functionality that makes sense, there's nothing keeping you from marking the method itself as abstract, requiring that derived classes implement it themselves, just like if they were to implement an interface.

For answers to questions like this, I often turn to the .NET Framework Design Guidelines, which have this to say about choosing between classes and interfaces:

In general, classes are the preferred construct for exposing abstractions.

The main drawback of interfaces is that they are much less flexible than classes when it comes to allowing for the evolution of APIs. Once you ship an interface, the set of its members is fixed forever. Any additions to the interface would break existing types implementing the interface.

A class offers much more flexibility. You can add members to classes that you have already shipped. As long as the method is not abstract (i.e., as long as you provide a default implementation of the method), any existing derived classes continue to function unchanged.

[ . . . ]

One of the most common arguments in favor of interfaces is that they allow separating contract from the implementation. However, the argument incorrectly assumes that you cannot separate contracts from implementation using classes. Abstract classes residing in a separate assembly from their concrete implementations are a great way to achieve such separation.

Their general recommendations are as follows:

  • Do favor defining classes over interfaces.
  • Do use abstract classes instead of interfaces to decouple the contract from implementations. Abstract classes, if defined correctly, allow for the same degree of decoupling between contract and implementation.
  • Do define an interface if you need to provide a polymorphic hierarchy of value types.
  • Consider defining interfaces to achieve a similar effect to that of multiple inheritance.

Chris Anderson expresses particular agreement with this last tenet, arguing that:

Abstract types do version much better, and allow for future extensibility, but they also burn your one and only base type. Interfaces are appropriate when you are really defining a contract between two objects that is invariant over time. Abstract base types are better for defining a common base for a family of types.

by anonymous   2017-08-20

The difference between VBA and VB.NET is just because VB.NET compiles continuously in the background. You'll get an error when you compile the VBA.

Like Jonathan says, when programming you can think of VB.NET as case-insensitive apart from string-comparisons, XML, and a few other situations...

I think you're interested in what's under the hood. Well, the .NET Common Language Runtime is case-sensitive, and VB.NET code relies on the runtime, so you can see it must be case-sensitive at runtime, e.g. when it's looking up variables and methods.

The VB.NET compiler and editor let you ignore that - because they correct the case in your code.

If you play around with dynamic features or late-binding (Option Strict Off) you can prove that the underlying run-time is case-sensitive. Another way to see that is to realise that case-sensitive languages like C# use the same runtime, so the runtime obviously supports case-sensitivity.

EDIT If you want to take the IDE out of the equation, you can always compile from the command-line. Edit your code in Notepad so it has ss and SS and see what the compiler does.

EDIT Quote from Jeffrey Richter in the .NET Framework Design Guidelines page 45.

To be clear, the CLR is actually case-sensitive. Some programming languages, like Visual Basic, are case insensitive. When the Visual Basic compiler is trying to resolve a method call to a type defined in a case-sensitive language like C#, the compiler (not the CLR) figures out the actual case of the method's name and embeds it in metadata. The CLR knows nothing about this. Now if you are using reflection to bind to a method, the reflection APIs do offer the ability to do case-insensitive lookups. This is the extent to which the CLR offers case-insensitivity.

by anonymous   2017-08-20

I prefer to name my virtual or abstract methods with the suffix Core, to indicate, that the method should contain the core logic to do something.

All argument checks and raising possible events I do in the method, that calls the Core-Methods.

  abstract class Animal {
    public void Walk() {
      // TODO: do something before walking 
      // possible Argument checks and event raising

      // custom logic implemented by each subclass

      // TODO: do something after walking

    protected abstract void WalkCore();

  class Dog : Animal {
    protected override void WalkCore() {
      // TODO: walk with 4 legs

  class Bird : Animal {
    protected override void WalkCore() {
      // TODO: walk with 2 legs

I think there is no offical naming guideline for this, and it´s up to you. But it should be consistent for all classes and virtual/abstract methods you define.

The "Framework Design Guidelines" suggest to use the Core suffix if you follow the Template Method and want to provide extensibility points.