Our Privacy and Cookie policies have been updated.
Please read and understand these policies before continuing to use this website. Thanks.

C#6: Using Static Types and Extension Methods

This week I thought I would continue from the last couple of posts on the new language features introduced in C#6 and look at the changes to the using keyword.

Up until the latest syntax, using was overloaded in three different ways1.

  1. To import types from a specific namespace, reducing the need to fully quality those types when referencing them in subsequent code.
  2. To alias namespaces and types in order to resolve ambiguities when types share a name but different namespaces.
  3. To define a scope at the end of which an object will be disposed

With C#6 comes an additional overload that allows us to import methods from within a specific static class. By specifying the static keyword after using, we can give the name of a static class containing the members we want to import. Doing this allows us to reference the methods as though they were members of our class.

Using Static

Consider System.Math; prior to this updated syntax, using the various methods on the System.Math class would require either specifying the fully qualifed type name, System.Math or, if using System were specified, just the type name, Math. Now, by specifying using static System.Math we can reference the methods of the Math class as though they were members of the class invoking them (without a System.Math or Math prefix). In this example, Math.Abs() is called as just Abs().

As with other additions in C#6, this seems to be aimed at improving developer productivity as it leads to less overall typing when using the methods of a static class. However, the new using static syntax also allows for very targeted inclusion of static classes without the rest of their containing namespace, previously only possible with an alias, such as using Math = System.Math. This targeting ability, while not really adding anything for regular static methods, makes a significant difference for extension methods.

Extension Methods

As you probably know, extension methods are just fancy static methods, they can even be invoked as would a regular static method. However, extension methods can also be invoekd as though they where member methods of a variable or literal value. For example, both the following examples compile to the same code (assuming we have an enumerable called list).

However, before the using static syntax, including extension methods was a bit uncontrolled. If you wanted the extension methods in System.Linq.Enumerable, you had to include the entire System.Linq namespace; there was no way to include only the Enumerable static class. In some circumstances, this inability to include just the static class led to annoying type name clashes and occasionally unexpected overload resolution ambiguities or surprises. Now, with using static we can specify the exact class of extension methods we want to include and ignore the rest of the containing namespace.

With all that said, there is a notable difference between including regular methods of a static class and extension methods of a static class when importing via using static <namespace>.<static class>2.

Subtle Difference

When a static class is imported with using static, the way a method can be invoked depends on whether it is an extension method or not. For example, imagine we have a static class called MyStaticClass and it has a regular3 static method on it called Print that takes a string. When included via using static, Print could be used like this:

However, if instead Print were an extension method on type string, including MyStaticClass via using static would limit Print to being used like this:

Note how in both examples , Print can be invoked as a traditional static method when the containing type is referenced, as in MyStaticClass.Print(), but their invocation varies when using static imports the class. In that second scenario, non-extension static methods are invoked as though they are methods on the current type, where as extension methods are invoked only as though they are methods on a variable. For the extension method version of Print, the following is not allowed:

To use this argument-style syntax with an extension method, we must resort to the same syntax we would have used before using static, specifying the type name before the method:

Though I feel it is clear and intuitive, this is a subtle difference worth understanding, as it can lead to breaking changes. Consider if you were refactoring the methods of a static class from extension method to regular static method or vice versa, and that class were imported somewhere with using static; any invocations that were not prefixed with the static class name would fail to compile.

In Conclusion

Overall, I like the new using static syntax; I believe the differences in method invocation from how static class methods are normally invoked makes sense and I hope you do too. Like all the other features of C#, there will be times to use this feature and times to let it go in favour of something clearer and more appropriate. For me, the ability to pluck a specific class and its extension methods from a namespace without importing the rest of that namespace is the most useful aspect of using static and probably what I will use most. How about you? Do you see yourself adding using static to your coding arsenal, or is it going to languish in your scrapbook of coding evil? Do tell.


  1. The MSDN docs say two different ways, but it was clearly three and is now three and a halfish 

  2. However, unlike the subtle difference I highlighted in my last post, thankfully, the compiler will catch this one 

  3. as in not an extension method 

C#6: Auto-property Initializers and Expression-Bodied Properties

Last week, I discussed the new null-conditional operators added in C#6. This week, I would like to discuss two features that are awesome but could lead to some confusion: auto-property initializers and expression-bodied properties1.

Auto-initialized Properties

Before C#6, if we wanted to properly define an immutable property that had some expensive initialization, we had to do the following2:

Some people often use the shortcut of an auto-implemented property using the following syntax:

However, defining properties like this means they are still mutable within the class (and its derivations). Using a backing field with the readonly keyword not only ensures that the property cannot be changed anywhere outside of the class construction, it also expresses exactly what you intended. Being as clear as possible is helpful for anyone who has to maintain the code in the future, including your future self.

From what I have read and heard, the main driver for using auto-implemented properties was writing less code. It somewhat saddens me when clarity of intent is replaced by speed of coding as we often pay for it later. Thankfully, both can now be achieved using initializers. Using this new feature, we can condense all that code down to just this:

It is a thing of beauty3. Behind the scenes, the compiler produces equivalent code to the first example with the readonly backing field.

Of course, this doesn't help much if you need to base your initialization on a value that is passed in via the constructor. Though a proposed feature for C#6, primary constructors, would have helped with this, it was pulled from the final release. Therefore, if you want to use construction parameters, you will still need a backing field of some kind. However, there is another feature that can help with this. That feature is expression-bodied properties4.

Expression-bodied Properties

An expression-bodied property looks like this:

This is equivalent to:

Using this lambda-esque syntax, we can provide more succinct implementations of our read-only properties. Consider this code:

Using expression-body syntax, we can write it as:

But for the additional backing field declaration, this is almost as succinct as using an auto-implemented property. Hopefully, this new syntax will encourage people to make their intent clear rather than using the auto-implemented property shortcut when implementing immutable types.

Caveat Emptor

These new syntactical enhancements make property declaration not only easier to write, but in many common cases, easier to read. However, the similarities in these approaches can lead to some confusing, hard-to-spot bugs. Take this code as an example:

Here we have two properties: CurrentDirectory1 and CurrentDirectory2. Both seem to return the same thing, the current directory. However, a closer look reveals a subtle difference.

Imagine if the current directory is C:\Stuff at class instantiation but gets changed to C:\Windows some time afterward; CurrentDirectory1 will return C:\Stuff, but CurrentDirectory2 will return C:\Windows. The reason for this difference is the syntax used. The first property uses auto-initialization; it captures the value of Environment.CurrentDirectory on construction and always returns that captured value, even if Environment.CurrentDirectory changes. The second property uses an expression-body; it will always return the current value of Environment.CurrentDirectory, not the value of Environment.CurrentDirectory on construction of the MyClass instance.

I am sure you can imagine more serious scenarios where such a mix-up could be a problem. Do you think this difference in behavior will be obvious enough during code review or when a bug is reported? I certainly don't and I'm writing this as a way of reinforcing it in my own mind. Perhaps you have already dealt with a bug relating to this; if so, share your tale of woe in the comments.

In Conclusion..

I am by no means intending to discourage the use of these two additions to the C# language; they are brilliant and you should definitely add them to your coding arsenal, but like many things in software development, there is a dark side. Understanding the pros and cons of any such feature is important as it enables us to spot errors, fix bugs, and write good tests. This new confusion in the C# world is just another encouragement to code clearly, test sensibly, and be aware of the power in the tools and languages we use.


  1. No one else seems to by hyphenating "expression-bodied" but it doesn't make sense to me otherwise; what is a "bodied property"? 

  2. Yes, I know that System.Enviroment.CurrentDirectory isn't really expensive; this is for illustrative purposes 

  3. especially if you are keen on making sure your code expresses exactly what you mean 

  4. expression-bodied methods are also possible, but I'm not touching on that in this post 

C#6: Null-conditional operators

With the release of Visual Studio 2015 in July came C# 6. Each iteration of C# has tended to have a theme and if there were a theme for this one, it would be developer productivity; all the new features in C# 6 appear to be either improvements to existing features, or syntactical shortcuts to simplify common operations. One of those syntactical shortcuts is the ?. operator1, which is accompanied by the similar ?[] operator2.

These new operators are collectively known as null-conditional operators. Most, if not all C# developers have used the null-coalescing operator, ?? and found it to be brilliant…until the next step was to call a method or property on the result. Though (something ?? somethingelse).Property seems like it might be a good idea, there is rarely a suitable somethingelse that doesn't just feel like hack, so invariably, we resort to an if or the conditional operator, ?:3.

Or, if using an indexer:

In C# 6, the ?. and ?[] operators step up to help. These new null-conditional operators check the value on the left of the operator and, if it is null, return null, short-circuiting the remainder of the expression; if the value on the left of the operator is non-null, the expression continues according to precedence rules.

Using these operators, we can express our earlier code much more succinctly and without resorting to convoluted, hacky ?? chains.

There isn't much else to write about these simple operators except to draw attention to how ?. works with Nullable<T> types such as int?4. Consider the ?? operator. When the ?? operator is applied to a nullable type like int?, it either returns the value wrapped in that int? or the value evaluated from the right of the operator. That is to say that instead of needing to reference the Value property of the nullable directly, the operator does that for you. The following assignment works because x.Value is returned from the ?? operator, not x.

The ?. operator works the same way, which means the following does not make sense and won't compile; Value is not a property of int:

Whereas this will work just fine:

In Conclusion…

The null-conditional operators, ?. and ?[] provide some shortcuts that will no doubt lead to clearer code, and I welcome their addition to the C# language. I hope that you do to.

 


  1. aka, the one-eyed Elvis operator 

  2. the robot Elvis, or Howard The Duck 

  3. The two-eyed Elvis 

  4. also expressible as Nullable<int> 

Ad Free

This is just a quick post. There was news today about malicious ads in reputable1 ad networks that can "surreptitiously hijack" computers. Though the Google ad network, the network used by this site, was not one of the networks reported to have been exploited, I decided to pull all syndicated advertising from my blog. Google may never be affected by this issue, but I don't want to wait to find out.

As a result of the changes I have made, I have also updated my cookie and privacy policies to reflect the changes, so please review those.

I did not want to take this action2, but I feel it is warranted given the seriousness of the possible outcomes. The nature of advertising online needs to change; consumers need confidence that the sites they visit are safe, advertising networks need to vet the ads they syndicate, and browsers need to empower their users. For more information on the malicious ads, I recommend reading the article on Ars Technica; for more information about online advertising and what needs to change, I recommend reading "The ethics of modern web ad-blocking" on Marco.org.

Finally, if anyone out there is interested in sponsoring my humble blog, please let me know. All the best and safe browsing.


  1. to be taken lightly, I suppose 

  2. I was almost $10 off finally getting my cheque from Google and all I really wanted was to cover the cost of hosting 

Reputation Is No Substitute For Knowledge

Last week, I regrettably ventured back to answering questions on StackOverflow. The question that lured me back was this one:

Due to the general confusion over this operator, my answer, though correct, was down-voted and derided as entirely wrong. Worst of all, one of the main detractors had over 300k in reputation and, rather than try what I had suggested, spent their time telling me I was wrong as their own incorrect answer received all the up-votes. In the spirit of StackOverflow as I once knew it, I edited my answer and answered the comments, trying to clear up the confusion and get the question answered adequately. As my answer got down-voted, more incorrect answers got up-voted. However, eventually, I was able to convince my main detractor that my answer was correct. So they promptly deleted all evidence that they ever thought otherwise and, without attribution, edited their once incorrect, top-voted answer to be correct.

Though it stings a little1, I do not mind that my answer did not get accepted nor that it did not get the most votes; the question was answered correctly and that's the point of the site. What I find most disagreeable is the unsporting behavior that undermined the sense of community that once pervaded StackOverflow. I left the whole experience feeling like an outsider. In the past, those with wrong answers would delete theirs in favor of the right one, or they would edit theirs, but give credit to the right one. People would (in the most part) treat each other with respect and see reputation as a sign of being a good citizen, not necessarily a knowledgeable one. Not anymore.

I wish I could show the comments I received when answering this question, but they were deleted2. However, the general pattern of this and other experiences appears to be that someone with a high reputation score down-votes and derides other answers, then once the correct answer is clear, takes everything from the correct answers posted to edit into their own, which then earns all the reputation. It is an embittering experience that I know others have shared.

In the beginning, earning reputation and badges encouraged people to get things right and to help each other out. Now the site has matured, the easy questions are answered, and the gap between the newcomers and those with the highest reputation is huge. Newcomers languish in poverty with little opportunity, if any, to reach the top, while those at the top benefit from a bias toward answers and opinions that come from those with large reputation scores. What once incentivised good behavior and engagement, seems to have led to bullying and dishonesty. I am not saying that all people with high reputation engage in unscrupulous practices on StackOverflow —there are many generous and humble members of the community —unfortunately, bad experiences outweigh good experiences 5-1 (or as high as 12-1), so the actions of a few can poison the well.

The root of the problem as I see it3 is that reputation has become (or perhaps always was) over-valued, and in its pursuit, some have lost sight of what StackOverflow was trying to achieve; community. The community that made it special, that made me feel like I belonged, is gone, and reputation is no substitute for knowledge. What was once an all-for-one, one-for-all environment has, in the competition for reputation, turned toxic4.

I have no doubt that many reading this will think I am misrepresenting the situation, overreacting, or just plain wrong, and that is OK; I hope that those people are right, that this is not a trend, and that the overall community remains friendly and constructive. Personally, I will think twice before involving myself in answering (or even asking) a question on StackOverflow again.

Ultimately, StackOverflow works as long as the right answers get provided; but if those with the knowledge to answer get disillusioned and leave, from where will those right answers come?

Today's featured image is "Façade of the Celsus library, in Ephesus, near Selçuk, west Turkey" by Benh LIEU SONG. It is licensed under CC BY-SA 3.0. Other than being resized, the image has not been modified.


  1. we all like recognition for being right 

  2. I also deleted mine, since they were without context 

  3. if it is agreed that there is one 

  4. The fact that I even felt wronged may well be an indicator of that toxicity and my own part in its creation