Skip to content

.NET articles

5 simple steps to publishing a NuGet package  

There is a fair amount of info on making and publishing NuGet packages but I couldn’t find a simplified guide for the simple case. Here it is and start by downloading nuget.exe and putting it in your path.

1. Multi-platform considerations (optional)

Supporting multiple platforms gives you a choice to make:

  1. Portable Class Library (PCL)
  2. One project with MSBuild magic
  3. Multiple projects

If you can go with PCL do it. For CSharpAnalytics we use platform-specific system info and hooks so it’s not an option – we went with multiple projects.

Multiple projects

Creating a separate .csproj for each platform and putting in the same folder means adding files isn’t too painful (show all files then include the ones you need) but you do need to take steps to make sure the build process for the projects don’t interfere with each other by separating the bin and obj paths:

  1. Set the output path in the Build tab of project properties to be unique per configuration to for the bin files, e.g. “bin\Net45\Release\”
  2. Edit the .csproj file adding a BaseIntermediateOutputPath tag for obj files, e.g. <BaseIntermediateOutputPath>obj\Net45</BaseIntermediateOutputPath>

2. Create your .nuspec definition

Now that you know which release dll files you need to include you can go ahead and create the nuspec file that tells nuget how to package your files up.

Open a PowerShell and type nuget spec to create you an XML file to edit in your text editor

Once you’ve entered your author details, a snappy description and links to your project page and license you can then add the files. Libraries will want to copy the .dlls into the lib folder with element like these:

<file src="..\bin\Net45\Release\MyLibrary.dll" target="lib\net45" />

Each platform will require a specific target and they should use platform name (e.g. net45, sl5, windows8) described in the NuSpec creating packages documentation. That page has a lot more detail on things such as content file types etc.

If you prefer a graphical UI then NuGet Package Explorer will make your life easier.

Remember to check your .nuspec file to source control (there is nothing private in it) and add it to your solution as a solution item so it doesn’t get missed.

3. Create your .nupkg package

The easiest part of the process. From PowerShell type:

nuget pack yourfile.nuspec

If all goes well it will create yourfile.nupkg.

4. Test your package

Just because your package was created doesn’t mean it works and you don’t want to publish to the world until you know it works especially given you can’t delete packages from NuGet:

  1. Create a folder to be your own private testing NuGet repository, e.g. c:\testnuget
  2. Publish to your test repository with nuget push yourfile.nupkg -source c:\testnuget
  3. Configure Visual Studio to use your test repository by going to Tools > Library Package Manager > Package Manager Settings > Package Sources and then adding your test folder to the Available package sources test
  4. Create a new test application and then add a reference using Manage NuGet Packages to choose your new package from your test repository.
  5. Write a few lines of code to test you can actually use your package ok!

5. Publish to the world

Okay, you’re now ready to publish. If you haven’t yet signed up for an account over at you’ll need to do that first.

  1. Go to Your Account and copy your API key
  2. Run the PowerShell command nuget setApiKey followed by your API key, e.g. nuget setApiKey 99995594-38d2-42cd-a8b1-ddcd722bb7e7
  3. Run nuget push yourfile.nupkg again this time without the -source option to publish to the default public repository


Probable C# 6.0 features illustrated  

C# 6.0 is now available and the final list of features is well explained by Sunny Ahuwanya so go there and try it with his interactive samples page.

Adam Ralph has a list of the probable C# 6.0 features Mads Torgersen from the C# design team covered at new Developers Conference() NDC 2013 in London.

I thought it would be fun to show some before and after syntax for comparison and in doing so ended up with a few thoughts and questions.

1. Primary Constructors

Shorter way to write a constructor that automatically assigns to private instance variables.


public class Point {
    private int x, y;

    public Point(int x, int y)
        this.x = x;
        this.y = y;


public class Point(int x, int y) {
    private int x, y;


  • Do you need to independently define x and y?
  • Can you still write a body?
  • How would you make the default private?

This solution feels too constrained, would have preferred something like:

public Point(set int x, set int y)

That set the property and optionally created a private one if it didn’t. Would allow bodies, use on multiple constructors etc.

2. Readonly auto properties

Readonly properties require less syntax.


private readonly int x;
public int X { get { return x; } }


public int X { get; } = x;  


  • Love this.
  • Very useful for immutable classes.

3. Static type using statements;

Imports all the public static methods of a type into the current namespace.


public double A { get { return Math.Sqrt(Math.Round(5.142)); } }


using System.Math;
public double A { get { return Sqrt(Round(5.142)); } }


  • Not something I’ve run into often but no doubt very useful for Math-heavy classes.
  • Could be useful for Enumerable LINQ-heavy classes if it works with static extension methods.

4. Property Expressions

Allows you to define a property using a shorthand syntax.


public double Distance {
    get { return Math.Sqrt((X * X) + (Y * Y)); }


public double Distance => Math.Sqrt((X * X) + (Y * Y));


  • Small but useful syntax reduction.
  • Has nothing to do with System.Linq.Expression despite the name.

5. Method Expressions

Allows you to define a method using a shorthand syntax.


public Point Move(int dx, int dy) {
    return new Point(X + dx1, Y + dy1);


public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);


Same as Property Expressions.

6. Params for enumerables

No longer need to define your params methods as an array and force early evaluation of the arguments.


public void Do(params int[] values) { ... }


public void Do(params IEnumerable<Point> points) { ... }


  • Can have params methods for IEnumerable and array side-by-side? Probably not.
  • Is evaluation deferred until evaluated if you pass a single IEnumerable instead of a params?

7. Monadic null checking

Removes the need to check for nulls before accessing properties or methods. Known as the Safe Navigation Operator in Groovy).


if (points != null) {
    var next = points.FirstOrDefault();
    if (next != null && next.X != null) return next.X;
return -1;


var bestValue = points?.FirstOrDefault()?.X ?? -1;


Love it. Will reduce noise in code and hopefully reduce null reference errors everywhere!

8. Constructor type parameter inference

Removes the need to create static factory methods to infer generic types. This is helpful with Tuples etc.


var x = MyClass.Create(1, "X");
public MyClass<T1, T2> Create<T1, T2>(T1 a, T2 b) {
    return new MyClass<T1, T2>(a, b);


var x = new MyClass(1, "X");


  • Another great addition.
  • Does it understand list and collection initializers to automatically determine the generic types too?

9. Inline declarations for out params

Lets you declare the out variables inline with the call.


int x;
int.TryParse("123", out x);


int.TryParse("123", out int x);


  • Not a particularly large syntax reduction.
  • Shorter code for Try methods and DirectX.

Wrapping up

Hopefully there are a few more gems to come that would help reduce noise. Would especially like to see syntax that wired up an interface to an internal instance variable where not specifically overridden to aid in encapsulation, e.g.

public MyClass : IList => myList {
  private IList myList;

  public Add(object item) {
    // Do something first


8 things you probably didn’t know about C#  

Here’s a few unusual things about C# that few C# developers seem to know about.

1. Indexers can use params

We all know the regular indexer pattern x = something[“a”] and to implement it you write:

public string this[string key] {
  get { return internalDictionary[key]; }

But did you know that you can use params to allow x = something[“a”, “b”, “c”, “d”] ?

Simply write your indexer like this:

public IEnumerable<string> this[params string[] keys] {
  get { return keys.Select(key => internalDictionary[key]).AsEnumerable(); }

The cool thing is you can have both indexers in the same class side-by-side. If somebody passes an array or multiple args they get an IEnumerable back but call with a single arg and they get a single value.

2. Strings defined multiple times in your code are folded into one instance

Many developers believe that:

if (x == "" || x == "y")

will create a couple of strings every time. It won’t.

C#, like many languages, has string interning and every string your app compiles with gets put into an in-memory list that is referenced at runtime.

You can use String.Intern to see if it’s currently in this list but bear in mind that doing String.Intern(“what”) == “what” will always return true as you just defined another string in your source. String.IsInterned(“wh” + “at”) == “what” will also return true thanks to compiler optimizations. String.IsInterned(new string(new char[] { ‘w’,’h’,’a’,’t’ }) == new string(new char[] { ‘w’,’h’,’a’,’t’ }) will only return true if you have “what” elsewhere in your program or something else at runtime has added it to the intern pool.

If you have classes that build up or retrieve regularly used strings at runtime consider using String.Intern to add them to the pool. Bear in mind once in they’re there until your app quits so use String.Intern carefully. The syntax is simply String.Intern(someClass.ToString())

Another caveat is that doing (object)”Hi” == (object)”Hi” will return true in your app thanks to interning. Try it in your debug intermediate window and it will be false as the debugger will not be interning your strings.

3. Exposing types as a less capable type doesn’t prevent use as their real type

A great example of this is when internal lists are exposed as IEnumerable properties, e.g.

private readonly List<string> internalStrings = new List<string>();
public IEnumerable<string> AllStrings { get { return internalStrings; }

You’d likely think nobody can modify internal strings. Alas, it’s all too easy:


Even AsEnumerable won’t help as that’s a LINQ method that does nothing :( You can use AsReadOnly which creates a wrapper over the list that throws when you try and set anything however and provides a good pattern for doing similar things with your own classes should you need to expose a subset of internal structures if unavoidable.

4. Variables in methods can be scoped with just braces

In Pascal you had to declare all the variables your function would use at the start of the function. Thankfully today the declarations can live next to their assignment and use which prevents acidentally using the variable before you intended to.

What it doesn’t do is stop you using it after you intended. Given that for/if/while/using etc. all allow a nested scope it should come as only mild surprise that you can declare variables within braces without a keyword to achieve the same result:

private void MultipleScopes() {
  { var a = 1; Console.WriteLine(a); }
  { var b = 2; Console.WriteLine(a); }

It’s almost useful as now the second copy-and-pasted code block doesn’t compile but a much better solution is to split your method into smaller ones using the extract method refactoring.

5. Enums can have extension methods

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions {
  public static DateTime From(this Duration duration, DateTime dateTime) {
    switch duration {
      case Day:   return dateTime.AddDays(1);
      case Week:  return dateTime.AddDays(7);
      case Month: return dateTime.AddMonths(1);
      default:    throw new ArgumentOutOfRangeException("duration")

I think enums are evil but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

6. Order of static variable declaration in your source code matters

Some people insist that variables are ordered alphabetically and there are tools around that can reorder for you… however there is one scenario where re-ording can break your app.

static class Program {
  private static int a = 5;
  private static int b = a;

  static void Main(string[] args) {

This will print the value 5. Reorder the a and b declarations and it will output 0.

7. Private instance variables of a class can be accessed by other instances

You might think the following code wouldn’t work:

class KeepSecret {
  private int someSecret;
  public bool Equals(KeepSecret other) {
    return other.someSecret == someSecret;

It’s easy to think of private as meaning only this instance of a class can access them but the reality is it means only this class can access it… including other instances of this class. It’s actually quite useful for some comparison methods.

8. The C# Language specification is already on your computer

Providing you have Visual Studio installed you can find it in your Visual Studio folder in your Program Files folder (x86 if on a 64-bit machine) within the VC#\Specifications folder. VS 2010 comes with the C# 5.0 document in Word format.

It’s full of many more interesting facts such as:

  • i = 1 is atomic (thread-safe) for an int but not long
  • You can & and | nullable booleans with SQL compatibility
  • [Conditional(“DEBUG”)] is more useful than #if DEBUG

And to those of you that say “I knew all/most of these!” I say “Where are you when I’m recruiting!” Seriously, it’s hard enough trying to find C# devs with a solid understanding of the well-know parts of the language.


Designing a great API  

Several years ago I worked on a payroll package developing a core engine that required an API to let third parties write calculations, validations and security gates that would execute as part of it’s regular operation.

We were a small team and I had many conversations with another developer tasked with building a payroll using the API I would provide. Some methods here, classes there, the odd helper function and I had an API and then we had a mini payroll running.

Then he showed me the code he had written and that smug grin dropped off my face. It was awful.

Perhaps this other developer wasn’t as great as I’d thought? Looking at the code though made me realise he had done the best anyone could with a terrible API. I’d exposed parts of this core payroll engine with hooks when it needed a decision. Its job was to run the payroll – a very complex task that involved storage, translation, time periods, users and companies. That complexity and context had leaked out.

Unfortunately it’s not a unique story – many API’s are terrible to use. They’re concerned with their own terminology, limitations and quirks because they are exposed sections of an underlying system developed by those responsible for the underlying system.

If you want others to have a good experience with your product you have to put yourself in their shoes. Whether it’s a UI or an API makes no difference.

You are not the user

That’s the real difference between writing the classes that form your regular implementation and those that make up your public API.

We had time to fix our payroll API. Instead of refining and polishing here and there we took the 20 or so snippets developed for the mini payroll and pruned, cleaned and polished until they looked beautiful. They scanned well and made sense to payroll developers unfamiliar with our package. When a third developer familiar with payrolls but unfamiliar with out package developed the necessary code for a fully-functional jurisdiction in record time with minimal assistance we knew we had hit our goal.

Sure implementing that new API was hard work. Instead of simple methods sticking out of the engine we had a facade over our engine but it was justified. They were two different systems for two different types of user with distinct ideas about what the system was and how it was going to be used.

Code First

Many years later I found myself on a small team of 3 people tasked with putting a brand new API on top of Entity Framework for configuring models with code the .NET world would come to know as Code First. I was determined to use my experience and avoid another complex API surface littered with terminology and leaky abstractions. Parts of EF already suffered from that problem.

So for the first few weeks of that project we didn’t write any of the code that would in fact become Code First.

Instead we decided who our user was – in this case a C# developer who likes writing code, knows LINQ and some database concepts but doesn’t know Entity Framework as people who did were already using Model First or Database First.

Then we wrote tiny sample apps and tried to find simpler and simpler ways to describe them in code. We’d often start on a whiteboard with a scenario and write the complete mapping. We’d then try and find conventions that would remove the need for most of it and then try to write succinct code to configure the rest. As the newest guy to the team I’d fight to keep EF terms away from the main API surface in order to reduce that barrier to entry and help drive adoption.

Finally we’d hit the computer and develop stub classes and methods to make samples compile and let us try the IntelliSense. This isn’t always necessary but if you want to develop a fluent API or provide lots of type-safety such as Code First’s relationship mapping it’s highly recommended.

We’d then revisit the samples later and see if they could be read as easily as they were written and figure out what problems people were likely to run into and whether we could solve them without too much noise. Sometimes this meant having more than one way to do things such as chaining the fluent methods or allowing a bunch of properties to be set (solved with an extension method class providing the fluent API) and how users could manage larger models (solved by subclassing EntityConfiguration<T> – now EntityTypeConfiguration<T> sigh – and allowing redundant specification for things like relationships that span more than one class).

We finally ended up with succinct code like this with IntelliSense guiding you along the way and preventing you from even being able to specify invalid combinations. The HasMany prompts the properties on Customer and it won’t show you WithRequired unless it is valid. In the case of Required to Required it will ensure that the WithRequired specified which end is principle and dependent. In short it guides you through the process and results in highly readable code.

Entity<Customer>().HasMany(c => c.Orders).WithRequired(o => o.Customer).WillCascadeOnDelete();

This process took a little longer but given the amount of use the API will get that time will be saved by users countless times over.

Code First went down incredibly well with both the target audience and existing EF users and inspired the simpler DbContext interface that became the recommended way of accessing EF.

I think it’s one of the nicest API’s to come out of Microsoft and .NET.


PS. Martin Fowler has some great guidance in his book Domain Specific Languages.