Existing implementations inherit the default implementation. This language feature enables API authors to add methods to an interface in later versions without breaking source or binary compatibility with existing implementations of that interface. You can now add members to interfaces and provide an implementation for those members. This feature lets you specify your design intent so the compiler can enforce it, and make optimizations based on that intent.įor more information, see the readonly instance members section of the Structure types article. The following method won't compile unless you remove the readonly modifier: public readonly void Translate(int xOffset, int yOffset) The compiler does enforce the rule that readonly members don't modify state. Auto-implemented properties are an exception the compiler will treat all auto-implemented getters as readonly, so here there's no need to add the readonly modifier to the X and Y properties. The compiler doesn't assume get accessors don't modify state you must declare readonly explicitly. Notice that the readonly modifier is necessary on a read-only property. The Distance property doesn't change state, so you can fix this warning by adding the readonly modifier to the declaration: public readonly double Distance => Math.Sqrt(X * X + Y * Y) The compiler warns you when it needs to create a defensive copy. The preceding change generates a compiler warning, because ToString accesses the Distance property, which isn't marked readonly: warning CS8656: Call to non-readonly member '' from a 'readonly' member results in an implicit copy of 'this' Public double Distance => Math.Sqrt(X * X + Y * Y) Consider the following mutable struct: public struct Point It's more granular than applying the readonly modifier to a struct declaration.
It indicates that the member doesn't modify state. You can apply the readonly modifier to members of a struct. Set the current directory to the csharp8 subdirectory for the try-samples repository.Clone the dotnet/try-samples repository.You can explore these features in your environment using the dotnet try global tool: Where in-depth articles are available, links to those tutorials and overviews are provided. The remainder of this article briefly describes these features. For more information, see C# language versioning.