Raw string literals in C# 11

Today I learned about raw string literals introduced in C# 11. The big improvement to me is that you don鈥檛 need to escape double quotes. So no more of this noise if you need a json string: string json = @" { ""number"": 42, ""text"": ""Hello, world"", ""nested"": { ""flag"": true } }"; You can now write: string json = """ { "number": 42, "text": "Hello, world", "nested": { "flag": true } } """; The other nice feature is that an extraneous indentation will stripped out based on the location of the closing """....

November 18, 2024 路 1 min 路 Brandon Pugh

Collection expressions

Today I learned that C# 12 is getting some nice javascript-like syntax with collection expressions and the .. (spread operator): string[] moreFruits = ["orange", "pear"]; IEnumerable<string> fruits = ["apple", "banana", "cherry", ..moreFruits]; Note though that the spread operator is only 2 dots instead of 3 dots like in javascript.

December 14, 2023 路 1 min 路 Brandon Pugh

Calling an extension method on a null instance

Today I learned that you can call an extension method on a null instance of the type. I had always assumed without thinking about it too hard, that the reason string.IsNullOrEmpty isn鈥檛 defined as an extension method in the framework is because you would get NullReferenceException. But if we were to define an extension method like public static bool IsNullOrEmpty(this string s), and call it like if(s.IsNullOrEmpty()) this is just syntactic sugar for if(StringExtensions....

October 19, 2023 路 1 min 路 Brandon Pugh

Ternary in C# string interpolation

Today I learned you can have ternary expressions inside of interpolated strings, you just need to wrap it in parenthesis: $"{timeSpan.Hours} hour{(timeSpan.Hours > 1 ? "s" : "")} ago"

August 23, 2023 路 1 min 路 Brandon Pugh