Dotnet StringSyntaxAttribute

Today I learned about the StringSyntaxAttribute added in .NET 7. It鈥檚 a handy attribute you can add to string properties to specify exactly what format the string should be in. This gives you extra IDE assistance like syntax highlighting and intellisense 馃敟. And you can also use a comment like /*lang=xxx*/ for regular variables. Read Steve鈥檚 post for more detail.

Type check and cast

Today I learned that you can use pattern matching in C# to check for a type and cast to it in the same expression. See the docs for more details. Microsoft even has a lint rule for it. if (x is Fruit) // Noncompliant { var f = (Fruit)x; // or x as Fruit // ... } if (x is Fruit fruit) { // ... }

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 """. 馃敟 ...

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.

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.IsNullOrEmpty(s)) and therefore it鈥檚 safe to call on a null instance. ...

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"

GetUnderlyingType

In c# Nullable.GetUnderlyingType(type)will return null if the type is not Nullable<T>. For some reason this is not what I expected.