The internals of the .NET Dictionary class are a common interview topic, so the information in this post might come in handy one day. You could also use this new-found knowledge to impress friends and colleagues at every opportunity! In this post, we’ll look at the generic Dictionary<TKey, TValue> (#) type. We'll look at how values are stored and retrieved. We'll see how hash codes are handled,…
Mocking frameworks are a path to insanity! They start out great. They're a great way to mimic methods. They initially save time. But they're a gateway drug that will ultimately break your encapsulation, break your builds, break your tests, and break your mental capacity to understand what's going on! This post describes why I prefer using in-memory test doubles over mocking frameworks for all but…
When it comes to documenting projects, it is challenging to know where to start. It is challenging finding the first few words. After the first few words, it gets slightly easier until the next full stop. You pause. You think of something else to write. You write it and then pause again. You've now written a few things down, but how do they relate? Should the reader somehow be steered around this…
This post is an overview of code coverage metrics in .NET using Coverlet. In this post we'll: go through creating a simple solution containing two projects, one containing production code and one containing tests set up Coverlet and look at how coverage metrics are calculated see how metrics change when code is added, removed, or changed look at the different formats of reports see how code…
In this post, I would like to introduce a new code smell: The Pernicious Nulls Code Smell The propagation of nulls throughout a codebase that obscure ideas and concepts At least I think it's new; there are smells/anti-patterns about the dangers of using null, but this one focuses on the understandability of software that's infused with nulls. Nulls can spread throughout a codebase like garden…
Ever wanted to see all your configuration values in a .NET app? Ever wrote your own code to enumerate all those values? Me too, and we've both wasted our time! This quick post shows how to use the GetDebugView extension method on IConfigurationRoot which does exactly that. It has changes coming in .NET 7 that I'll show too. I wasn't aware of this extension method until recently, when I was looking…
This quick blog post shows one solution to a problem that you might have when binding to configuration ( appsettings.json or similar) in your .NET app. The problem: # I want to bind a collection from config, but if the config doesn't exist, I want to use some default values. I want either what's in config, or the default values, but not both For instance, given this type: public class…
Throwing exceptions in C# seems straightforward enough. You check for a certain situation and throw if it is an exceptional situation. However, just by having the code that throws an exception in your method can be inefficient, even if the exception is never thrown. Coming in C# 11 is a new feature named Parameter Null Checking . It's available at the time of writing in .NET 7 Preview 1 . This…
I recently received a GitHub issue for Vogen . It was a proposal to add the DebuggerTypeProxyAttribute . I was familiar with a few of the debugger related attributes, but not this one. So I've thrown together this post with my findings on the various debug related attributes. You never know, they might help you when you're next debugging ( debugging someone else's code , obviously! )…
This quick reference post shows how to fix the following error: System . TypeInitializationException : The type initializer for 'Microsoft . Data . Sqlite . SqliteConnection' threw an exception . -- -- System . Reflection . TargetInvocationException : Exception has been thrown by the target of an invocation . -- -- -- -- System . Exception : Library e_sqlite3 not found The scenario where this…
In this post, we'll look at non-defaultable value types and type invariants . At the time of writing, neither of these things exist in C#. We'll also look at a .NET library that I recently did named Vogen which combines source generation and code analysers to help bridge the gap while we wait for these things to come to C#. Non defaultable value types # Non-defaultable value types are similar in…
This is a very brief post about how to handle long-running requests in your ReST API. Sometimes, requests can't be handled immediately and your API should return information to the caller so that they can check the progress. If you have a ReST API endpoint that takes a long time to process requests, it is common practice to return a 202 Accepted response and include a header with a link to an…
This is a really short post describing a change to Resharper's (R#) code analysis for dead code. TL;DR: when C# 8 came along with Nullable Reference Types, R# turned off some of its analyses in #nullable enabled contexts and lost its ability to see dead code. The slightly longer version follow: R# warns you about dead code. Given the following code: public class Foo { public void DoSomething (…
A while back I wrote a clone of Pac-Man in Blazor WebAssembly . This post is about updating it to use any useful features of .NET 6 and C# 10. If this kind of thing interests you, you might also like to read the post I did last year about upgrading it to .NET 5 and C# 9 . If you just want skip all this, you can play it right now! Like last time, this is a rather rambling post that describes what I…
This short post looks at whether or not we should test our logging code. Spoiler alert: the short answer is Yes; the long answer is Yes, of course! But why, and what would it look like? Logging originated from the act of chopping down trees for wood keeping a seafaring journal onboard a ship for navigational purposes. They tracked a ship's movement and oriented sailors to their locations.…
This post looks at Generic Math which is coming (in preview form) in .NET 6. Generic Math ( which roughly translated into English means "Generic Maths" ) is the ability to use arithmetic operators on generic types . To give a quick example of what problems it solves, see that this isn't currently possible in C#: public T Add < T > ( T left , TRight ) => left + right ; Generic Math makes this…
This short post looks at an implementation of a dictionary that is optimised for keys of generic types. It uses a 'trick' which gives it far better performance than that of a normal Dictionary<Type, TValue> . Using dictionaries that are keyed by a Type is quite common and is often used in 'hot paths', so this optimised lookup could save you precious processing time! I discovered this neat type via…
💡 UPDATE 2024: This post described the performance hit on using a now-obsolete package named 'StringlyTyped. ValueObjects'. There is a newer project that does not have the same performance impact, named Vogen . But be aware that there are value object libraries still out there that do have the issues described in this post. In my previous post , I covered what PrimitiveObsession is and how…
Primitive Obsession means being obsessed with primitives. Thanks for reading, see you next time! But to elaborate more: " Primitive Obsession is using primitive data types to represent domain ideas " # It is also known as StringlyTyped where important domain objects are represented as strings . It is this : int customerId = 42 It is being obsessed with the seemingly convenient way that primitives,…
What happens when you build a .NET app? What happens the instant you run it? The last time I studied this was when .NET Framework was in its infancy. That was nearly 20 years ago! Things have changed in those two decades: apps are now cross-platform; .NET has lost its "Framework" moniker; and I've lost my hair! This post looks at: what's in a modern .NET 5 (C#) project what's generated when you…
This post is about my recent experience of contributing to .NET, which has been open source since late 2014. I've nosed around the github repo several times as I'd always intended to contribute back to the project. So, after just 7 short years, I made the effort and contributed a change! In this post, I'll describe how to find something to work on, the steps to get and build the runtime (on…
SOLID is an acronym for a bunch of object-oriented principles. Actually, no. Not any more. SOLID is now just an ACRONYM ! Forget everything you knew or thought you knew of these principles , because they're all wrong, AND THEY'RE NOT EVEN PRINCIPLES! ... bit harsh... but there's been discussions in the community about these principles that people have been using for years as a guide for good…
ReSharper has many code inspections and most of them can have their severity set in R#'s configuration files ( .dotSettings ). Instead, I wanted to set them in .editorconfig files, so this post is about that as a reference/reminder to myself and for anyone else that lands here via a search engine. TL;DR:! # To turn off specific R# warnings in a certain folder, put an .editorconfig file in that…
A while back I wrote a clone of PacMan in Blazor WebAssembly and this post is about updating it to .NET 5. If you only recognised the word PacMan (and possibly Updating) in that sentence, then you won't find much of interest here, so skip this nonsense and just go and play it! Just so you know, this is a rather rambling post that describes what I did, and isn't a definitive list of C# 9 / .NET 5…
Ever thought about why the default C# convention differentiates between private and public fields: privates being _camelCased and publics being PascalCased ? Ever wondered why that same default convention doesn’t differentiate between private and public methods ? My convention, like the Java convention, is to make that differentiation between private and public methods. I quite often have this…
Mine were until I discovered new COMMON SENSE! ® TL;DR: I did something stupid and realised my mistake – what follows is mainly for future reference and for those that are making the same mistake. Win2D is great! So is the concept of UWP and the Windows Store. It means you can write a game for the Windows Store (for Windows 10), and with some minimal work, it can run on the XBox One (since that’s…
Probably of no interest to anybody (apart from my son who I did it for), but here’s a timelapse video converting Pac-Man from TypeScript (play it here) to C# for the Windows 10 Store. When it’s finished, I’ll put the source up and describe what I learnt during the process. Watch it here . Update November 2024 - links to the game removed - you can play a Blazor WebAssembly version here ( source…
I’ve been working with C# for many years now and the new additions to the language are very exciting. They’re focused on immutability. Well, actually, the Microsoft documentation seem to suggest they’re more focused on Performance, but they go hand-in-hand; the less you can modify, the faster things are. The benefits of immutability are often overlooked especially by those who have only…
Update April 2021 - I also did a version in Blazor WebAssembly and wrote about it here “If Pac-Man had affected us as kids, we’d all be running around in dark rooms, munching pills and listening to repetitive electronic music” Markus Brigstocke In my previous post, I wrote about learning TypeScript by writing a game . The game I chose was Pacman ( play it here ). I never intended to make the…
Want to learn a new programming language? Tired of the usual Line-of-Business tutorials? Then write a game! I’ve always said that the best way to learn a new language is to write a game with it. You’ll come across many problems when writing a game that you just won’t experience by writing an app that selects product items from a customer’s order. That’s what I did recently when I wanted to learn…
I’ve spent some time over the Summer and Autumn of 2011 rewriting the Gleed 2D tool . This is a tool for editing levels for 2D games and is a very popular tool in the XNA community for games running on XBox and Windows Phone. Most of the changes in the new version are under-the-hood. The biggest change has been to make it have a plug-in architecture. There has also been a few UI changes though;…
I recently needed a fast way of converting lots of enums to strings (and back again). I needed to do it very quickly. ‘Enum.Parse’ just wasn’t fast enough. I discovered there was no ‘enum mapper’ in C#, so I knocked up this little class . It uses reflection just once when it comes across a new enum. It’s compatible with .NET 3.5 too.
I don’t like to overuse if/else statements. I really dislike seeing code like this: if ( somethingIsTrue ) { DoSomethingWhenTrue ( ) ; } else { DoSomethingElse ( ) ; } I just had an idea about using extension methods so I can write this instead: somethingIsTrue . Branch ( ( ) => DoSomethingWhenTrue ( ) , ( ) => DoSomethingElse ( ) ) ; and here’s the extension method: public static void Branch (…
“Summon Method” A method that gets or creates something. A common question (well, I’ve seen it asked a few times), is what should I call a method the gets or creates something? Instead of Foo GetOrCreateFoo ( ) use: Foo SummonFoo ( ) What do you think?
Update: the source is now on GitHub Visual Studio 2010 is almost here. Visual Studio 2010 (the release candidate) is here . I’ll describe the problem before I describe the tool: You want to use the latest version of Visual Studio but you don’t want it to modify all of your projects and solutions because you’ve got other team members who don’t want to (or can’t) switch to 2010. A serious problem…
This plug-in formats and highlights code. Version 2.0.0.3 can be downloaded here . Keep reading for more info. As well as a few bug fixes, this release includes the following features: · Use different formatting engines such as ActiPro (Insert formatted code), and SyntaxHighlighter (Insert highlighted code) · Dozens of languages, including PowerShell, MSIL, Pascal and XAML · Live formatting of…
A while back, I wrote a blog post about how turning on Forms Authentication caused problems with stylesheets and Themes. A lot of people found this post useful but had trouble finding it. One reader suggested I change the title to get more hits. So, I did, and this is it.
I don’t know how I missed this for so long, but JetBrains have released a preview of ReSharper for Visual Studio 2010 ! They say this version is neither 4.5.1 nor 5.0, but a preview build with some of the new 5.0 features enabled. Looking at the nightly builds, it seems that the first release was 9th July, but there was no news on their blog, which I’ve been checking daily since June (when they…
Google Squared looks like an interesting tool. “Google Squared is a search tool that helps you quickly build a collection of facts from the Web for any topic you specify. Facts about your topic are organized as a table of items and attributes (we call them "Squares" for fun). Customize these Squares to see just the items and attributes you’re interested in. See the websites that served as sources…
Tree Trim is a command line tool that trims your source code tree. It removes debug files, source control bindings, and temporary files. It’s integrated with Windows Explorer: when you right click a folder you’re given the option to clean the folder. Massive thanks to Scott Hanselman for blogging about it and for providing some great and detailed feedback. If you’re interested in doing your own…
Version 2.0.0.2 of the Code Formatter Plugin can be downloaded here . This has a fix for when the plugin tried to load configuration from the wrong location on disk.
I’ve recently been working on a tool based on Jeff Atwoods Clean Sources Plus . It’s called TreeTrim . It’s a tool that strips out debug files and folders in your source code tree and also zips and emails amongst other things. One of the BIG requests for CleanSourcePlus (well, amongst the 5 people in the comments section of the tool’s page!) is for the tool to make a working copy of your source…
Version 2.0.0.1 of the Code Formatter Plugin is now available. New in this version: Enhanced support for Syntax Highlighter 2x You can now specify things such as tab size , show ruler , collapse , show toolbar , show line numbers , starting line number , and highlighting specific line numbers . Configuration screens for the different providers You can now add and remove languages and generally…
Types that implement IDisposable usually do so for a reason. They probably consume resources that should be released as early as possible. In a recent project, I came across a very neat idea. In the destructor/finalizer/finaliser of your IDisposable type, do something to alert the consumer that you’re being collected by the Garbage Collector and hence you haven’t been disposed of correctly. But…
Version 2.0 of the Code Formatter Plugin for Windows Live Writer is now available. New in this version is the ability to use different formatting engines – in this version: ActiPro and SyntaxHighlighter 2.0 Also new is the ability to output either formatted code as text or as a bitmap. A massive thank you to ActiPro for donating the ActiPro Syntax Editor component – the best code editor available!…
I’m a big fan of mind maps. I use MindManager , but there’s now an online Silverlight alternative from DropMind . It’s currently in beta, so there’s a few things that need addressing to make it as nice to use as MindManager (such as keyboard navigation). Despite this, it looks feature packed compared to other online mind mapping tools I’ve tried. There’s also a desktop version. It has none of the…
StyleCop has a law rule named SA1201 . It says that you should put various parts of your code in the correct order. For the contents of a class this goes like: Fields Constructors Finalizers (Destructors) Delegates Events Enums Interfaces Properties Indexers Methods Structs Classes Doing all this by hand is tedious, but as with most things, ReSharper (R#) makes it easier! R# has a couple of…
I like StyleCop but I didn’t like the fact it produced warnings on private fields and methods. I was wrong. Not wrong in that I didn’t like warnings on privates, but wrong that I thought there was no way to tell it to stop it. Apparently there is. Jason Allor kindly left a comment saying that it can be configured through the StyleCop settings dialog in Visual Studio. I took a look and initially…