In my previous post about Resharper over 2 years ago I was looking at the constructor injection refactoring help. The other day I came across another one following on from that which I’d not seen before.

Have you ever had a constructor which takes an enum as a dependency? No? Neither had I until recently. This will likely not happen with services and dependency injection (although I’d imagine you could do something with factories) but more when you are wanting new up a specific type of POCO. This was my scenario.

Let’s look at the below as a basic example; we have a simple enum and a poco which takes a Category in it’s constructor.

public enum Category
{
	Cars,
	Bikes
}

public class Transport
{
	private readonly Category _category;

	public Transport(Category category)
	{
		_category = category;
	}
}

With the carot on the category constructor parameter and pressing the magic Alt + Enter combination you get offered the option of “Check if enum parameter is defined by enum type”. Sounds interesting.

I’d not seen this before as injecting an enum into a constructor is not something I often do. On selecting the option the following was produced.

public class Transport
{
	private readonly Category _category;

	public Transport(Category category)
	{
		if (!Enum.IsDefined(typeof(Category), category))
			throw new InvalidEnumArgumentException(nameof(category), (int) category, typeof(Category));
		_category = category;
	}
}

Impressive!

Now personally I would wrap the throw in braces so I will probably go and update the template for this option now I know it’s available, but still just another glimpse of the power.

Remember though …

With great power comes great responsibility.

Any questions/comments then please contact me on Twitter @WestDiscGolf