-
Notifications
You must be signed in to change notification settings - Fork 4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
CS8852: Init-only property cannot be assigned to in an 'init' accessor if accessing it requires a cast (e.g. an explicitly implemented interface type) #50053
Comments
Same problem bugs me out. Is it intentional? if so why? |
In the cases the cast is an identity preserving conversion on |
LDM confirmed that this is by-design. If a base type needs to expose something to initialize, it should expose APIs to do so. |
What API? Can't do this through an interface since that introduces public API to circumvent the init-only-ness. Awkward. |
Simply using a public interface implementation would do it:
Note there is a similar problem that's already existing with a private implementation with
|
I think it could be something like this: public interface ISomething {
int Property { get; init; }
}
public record BaseType : ISomething
{
protected int SomethingProperty { get; init; }
int ISomething.Property {
get => SomethingProperty;
init => SomethingProperty = value;
}
}
public record DerivedType : BaseType
{
public int SomethingElse {
get => SomethingProperty;
init => SomethingProperty = value;
}
} |
I find at the very least the error message very confusing. It is also very weird to me that this works, but not the original code in the issue, with the only difference being that I don't want public interface ISomething { int Property { get; init; } }
public record BaseType : ISomething { public int Property { get; init; } }
public record DerivedType : BaseType {
public int SomethingElse {
get => Property;
init => Property = value;
}
} |
Version Used:
Using "Csc" task from assembly "C:\Program Files\dotnet\sdk\5.0.200-preview.20601.7\Roslyn\Microsoft.Build.Tasks.CodeAnalysis.dll".
Steps to Reproduce:
Try to compile this.
Expected Behavior:
Compiles.
Actual Behavior:
error CS8852: Init-only property or indexer 'ISomething.Property' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
The text was updated successfully, but these errors were encountered: