Read-only members in structures
With C# 8.0, now you can apply a read-only modifier to the members of a structure. This new feature is to provide read-only attributes to individual members of a structure.
Earlier this was only possible at the whole structure level.
Let us Understand this with an example:
public struct MathsOper
{
public int var { get; set; }
public int var1 { get; set; }
public readonly double sum => (var + var1);
}
The readonly modifier is necessary on a read-only property.You will need to explicitly add readonly specifier.
Auto-implemented getters are read-only by default and the compiler will treat them as read-only.
Default interface methods
Interfaces are core features of C# and Interfaces do not allow the function definitions. But with C# 8.0 now there is an additional feature for interfaces.
With C# 8.0, you can now add members’ functions to the interfaces and also provide the code implementation of those members. This feature will help developers to add functionality to interfaces.
Let us understand this with an example below:
interface ILogging
{
public void WriteLog()
{
Console.WriteLine("Log from Interface!");
}
}
With these news enhancements, there was a risk of breaking the application which is in the field already but to avoid that challenge this new enhancement is made backward compatible.
If someone wants to change the existing interface then it will not impact the existing application interfaces. But as a point of caution, this needs to be handled with care.
Static local functions
With the introduction of C# 8.0, now we can add the static modifier to local functions. This will help to ensure that the local function doesn’t capture any reference variables from the enclosing scope.
In C# 8.0 if you will try to capture a reference in a local static function then the compiler will flag you will an error at compile time itself.
Let us understand this with an example:
int Maths()
{
int var = 2;
int var1 = 6;
return Add(var, var1);
// Local static function
static int Add(int val, int val1) => val + val1;
}