New features in C# 11 (NET 7) with interactive examples
.NET 7 was released in Nov 2022. It includes C# 11 with a whole bunch of enhancements and quality-of-life improvements. I will describe some of these new features and provide interactive .NET Fiddles to try them out.
Require Members
Require modifier ensures that the property is initialized when the object is created.
public class Customer
{
public required string Email{ get; set; }
}
var customer = new Customer { Email = "Dave" };
var customer = new Customer(); //compilation error
Interactive Fiddle: https://dotnetfiddle.net/SOgr0t
Long strings with quotes and JSON
To simplify displaying a string with many quotes, we can use triple quotes to delimit such string. You can also interpolate it with $ or $$ or $$$ or…
The number of $ signs matches the number of curly brackets you would use for referencing variables.
//Long quote with indent and quoted text
string JsonRequest1 = """
This is a long quote.
It has several lines.
With indented
With "quoted text" in them.
""";
//$$ to interpolate. Just $ is not enough becuase single quotes are valid json chars
string val = "SomeValue";
string jsonRequest2=
$$"""
{
"value": "{{val}}"
}
""";
//$$$$$ to interpolate. Number of $ will match number of { and } usef for interpolaiton
//this way you can handle when {{...}} is valid text, for ex.
string jsonRequest3=
$$$$$"""
{
"value": "{{{{{val}}}}}"
}
""";
Interactive Fiddle: https://dotnetfiddle.net/6qQQxt
Generic attributes
Previously if you wanted to use a custom type in the attribute, you would have to introduce a new field of type Type and use unsafe syntax to check if provided type in the attribute is the correct one.
Like this:
public class TypeAttribute : Attribute
{
public TypeAttribute(Type t) => ParamType = t;
public Type ParamType { get; }
}
[TypeAttribute(typeof(string))]
public string SomeMethod() => default;
Fiddle: https://dotnetfiddle.net/U7L6rj
But with C# 11 you can just use generics:
public class GenericAttribute<T> : Attribute { }
[GenericAttribute<string>()]
public string SomeMethod() => default;
Fiddle: https://dotnetfiddle.net/JrddvM
The difference seems a bit superficial, but there are some good benefits to using Generic Attributes:
* Code completion/Build time error checking
* Performance, no more runtime checks for a given type
* Safe casting and better code completion
List patterns
It is kinda like RegEx for lists, so you can easily check if the list starts or ends with certain values and if it is of a certain size.
var list1 = new int[] {1, 2, 3, 4};
//Is same as [1, 2, 3, 4]? true
var result1 = list1 is [1, 2, 3, 4];
//Is same as [1, 2, ]? false
var result2 = list1 is [1, 2, 3];
//must start with 1 and end with 4. array of size 3? false
var result3 = list1 is [1, _, 4];
//first item is 1, last item >= 4, array of any size? true
var result4 = list1 is [1, .., >=4];
Fiddle: https://dotnetfiddle.net/mbDZkx
Newlines in string interpolations
The text inside the { and } characters for a string interpolation can now span multiple lines. The text between the { and } markers is parsed as C#, so this will improve readability.
int age = 34;
var msg = $"Question: {
age switch
{
< 3 => "What is that smell?",
< 15 => "Did you do your homework?",
< 25 => "When are you moving out?",
< 50 => "Where did the time go?",
< 65 => "Is it time to retire yet?",
_ => "What is that smell?"
}
}";
Fiddle: https://dotnetfiddle.net/apSXpt
Conclusion
In this article, we demonstrated some new features in C# 11 using interactive fiddles.
For a complete list of enhancements you can go here: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11