Saturday, May 30, 2015

.NET Generic Overloads: How to support T and IList

What happens when you want to overload a generic method where the first method accepts a single object and the other accepts an IList of that type?

It will only work when specifically try to pass in an IList. If you try to pass in a List it will fail because the compiler will identify the generic parameter overload and fail before trying to use the implicit cast to an IList.

This is because a C# compiler tries to identify overloaded methods it checks for matching parameters in the following order:

  1. Explicit type matches.
  2. Generic parameters.
  3. Implicit type matches.

Let's look at an example!

Example of what DOES NOT work.

public class OverloadSample1
    public void Test()
        // Matches Method A - Good
        ISample sample = new Sample();
        // Matches Method B - Good
        IList<ISample> samples1 = new List<ISample>();
        // Matches Method A - BAD!
        List<ISample> samples2 = new List<ISample>();
    // A
    public void Method<T>(T sample)
        where T : ISample
    // B
    public void Method<T>(IList<T> sample)
        where T : ISample
}, how do we solve this problem?

Saturday, May 23, 2015

How To Capture Test Output in xUnit 2.0

As of xUnit 2.0 the test framework no longer captures any native outputs, this is by design. Now the question is: where do you write your test output?

You now have to write all test output to an interface, ITestOutputHelper, that is injected into your test's constructor. This design seems to have polarized developers a bit, as not everyone enjoys being require to add a constructor to your test classes. Personally, as a huge fan of dependency injection, I really like this solution.

Spoilers: My next blog post will be about how to combine this with Common.Logging and NLog.

Sample Test

using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace XUnitDemo
    public class OutputTests
        private readonly ITestOutputHelper _testOutput;
        public OutputTests(ITestOutputHelper testOutput)
            _testOutput = testOutput;
        public async Task WriteLine()
            await Task.Delay(1000);


Thursday, May 14, 2015

Split your App.config into Multiple Files

What do you do when any file in your project becomes too big? You break it apart into multiple files!

Did you know that you can split your .NET configuration files into multiple files as well? Here is how...


<?xml version="1.0" encoding="utf-8" ?>
    <section name="customSection" 
    type="ConfigSectionDemo.CustomConfigurationSection, ConfigSectionDemo" />
  <appSettings configSource="AppSettings.config" />
  <customSection configSource="CustomSection.config" />
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />


  <add key="Hello" value="World"/>


<customSection goodnight="Moon">
Real Time Web Analytics