Writing “weakly typed” C#?

Because C# is a strongly-typed language… with a touch of leniency!

This article is also available on Medium.

If you’ve ever worked with C#, you know that this programming language is what we call a strongly-typed language: your variables, your constants and any expression that evaluates to a value must have a type. This type in turns determines what this “programming object” can and can’t do, where it can be used, what your IDE should show for auto-completion…

To accommodate for our everyday needs, the language offers quite a lot of built-in types (such as int, float, string…) and you can very easily import some core libraries like System.Collections.Generic to have Lists, Dictionarys, etc.

This is great because it insures that you are using the right kind of variable in the right place, and that for each and every line in your code you know precisely what sort of value you’re dealing with.

Note: other languages like Python, which don’t enforce typing and rather rely on duck-typing, can sometimes “fool” beginners by their simplicity… before you realise that you’ve accidentally replaced your value (integer) parameter with another (string) value computation in your function!

But sometimes, this typing can also be a bit heavy, overkill or even incomplete. That’s why, in C#, you can also benefit from implicit, anonymous and nullable types.

Trick n°1: Implicit types

Have you ever encountered the var keyword? That little tool is a very handy way of implicitly typing a local variable; this way, you don’t have to provide a type yourself – it’s the compiler itself that will infer it from the context at compile time.

Of course, this technique requires your variable to have a value when it is declared (otherwise the compiler won’t have anything to work from!). But it’s really cool to shorten your code: you can use it on local variables, in for or foreach loops, while using a file or a stream…

Note: be careful, though – you can’t use var for class members: it can only be used in the flow of your code!

Oftentimes, it’s very cool to use implicit types when working with the Linq utility. I’ve talked about it in details in this other article, but in short the Linq tool is a specific declarative query syntax that allows C# developers to easily parse, transform, extract, convert or organise data. By its very nature, Linq quickly has you play around with intermediary enumerables, temporary collections and other not-fully-determined transitional containers.

That’s why implicit typing can be great for this sort of use cases! 🙂

‘Cause if you have a somewhat “intelligent” IDE, you’ll be able to see that the real type of this variable is a tad more complex…

So initialising a variable with var doesn’t mean that it is untyped, or that it is lazily-typed: it’s just that the compiler will try and choose the best type for it. This means that your variable still has a given fixed type and, just like in any C# code, you can’t suddenly decide to change it in the midst of your process:

Personally, I really like the strong-typed “constraints” because I think they also insure really readable code; but I find var interesting when the explicit type would be really long to write, or when it’s a bit of headache to know the exact type of the result, like in complex grouping and sorting operations 😉

Trick n°2: Anonymous types

Now that we’ve talked about the var keyword, let’s discuss another cool feature of C# that makes use of it: the anonymous types.

Sometimes, there is some temporary read-only data that you’d like to use and “forget” immediately. For example, you may have a little message with a log level associated with it. In that case, anonymous types are a good way of having clearly typed and named properties inside of a throw-away data structure, like this:

Again, this is very useful when you work with Linq statements and want to “extract” some properties out of your objects just for this local scope – by creating an anonymous type during the query, you can get access to the values inside your initial items:

But you also protect the rest of the data, since it has been ignored by the type and isn’t exported in the result (here, you see I only have the name and age fields available):

Finally, note that you can create arrays of anonymous types with a new[] { ... } construct, and that starting from C# 10, it is now possible to mutate a property of an anonymous type using the with keyword (but you can only change a value – you can’t delete a property in your type):

Trick n°3: Nullable types

And to wrap up this little “weakly-typed C# journey”, I want to talk about nullable types 🙂

This time, we’re going to put the var keyword and the implicit types aside, and focus more on the value of the variable.

Suppose I give you the following challenge: setup a simple 2D character movement scheme to make the hero move left or right. Your first thought could be to encode the current movement direction as an integer, using -1 (moving left), +1 (moving right) or 0 (not moving). But now, I’m going to add another constraint: I want you to use a single boolean variable, movingRight.

Then you might be thinking: “fair enough, I’ll just say that movingRight = true when the hero’s moving right, and movingRight = false if the hero’s moving left!”.

But what about when the hero’s not moving? Wouldn’t it be nice to have a third “unassigned-value”?

This is doable, by using a nullable bool:

By the way – since we’ve “extended” our boolean and that it now has three possible values (null, true or false), you see that I need to check explicitly for movingRight == true otherwise the compiler can’t distinguish between the values properly:

Okay, I’ll admit this is a pretty far-fetched example. In real life, you’d hardly ever be forced to use a bool like this! But there are still plenty of cases where your variable can be undefined or missing at one point: an empty cell in a data source, an error while fetching the info… In all those situations, it’s interesting to clearly state that the variable has a null value, and not “some fallback value that we’re going to treat as a special case” 😉

To check whether the nullable variable is currently null or not, you can compare it to null directly, use its HasValue property or, in C# 7 and higher, use the is operator:

And of course, you can “convert” back a nullable type to its underlying type, like this:

As explained in the Microsoft docs, you can also play around with the variable’s type, its underlying type, boxing and unboxing, experiment with lifted operators, etc. 🙂


To me, C# is a really great language that cleverly balances fixed rules with shortcuts and handy syntactic sugar, or even implicit operations. It’s easy-to-use and yet safe and robust, even on large projects. For example, nullable types allow you to handle missing or undefined values, anonymous types let you isolate data chunks into readable and nice structures while you need them and implicit types are the key to writing short code and handling complex types!

I hope you like this article – feel free to leave a comment and tell me if you have other ideas for C# posts… and as usual, thanks a lot for reading 🙂

2 thoughts on “Writing “weakly typed” C#?”

  1. None of this is “weakly typed” this is just implicit typing. C# has unchecked types with the dynamic keyboard and you can even do unstructured data with expando objects. People just don’t use it because dynamic types are terrible.

    1. Hi! Hence the quotes around “weakly” 😉
      The point was to have a “catchy” title, but then expand more on some util notions and tools that not everyone knows about in C#. I’m not saying they’re a silver bullet, or that everyone should use it in every project – it’s just a quick peek at some specific C# feature so that some readers can discover a few things and try them out if they want…

Leave a Reply

Your email address will not be published.