Reputation: 648
I'm trying to create a readonly property (c# 7.2 feature).
public class JobStatus
{
public int Id { get; set; }
}
public class Job
{
public ref readonly JobStatus Status => ref _jobStatus;
private readonly JobStatus _jobStatus = new JobStatus
{
Id = 4
};
}
class Program
{
static void Main(string[] args)
{
var job = new Job();
job.Status.Id = 5;
}
}
This code compiles successfully. I would expect some kind of error that I'm trying to update field of readonly property. Am I using ref readonly return feature incorrectly?
Upvotes: 0
Views: 937
Reputation: 12796
From what I found in this article you should understand it as the following
Marking a parameter as “readonly ref” or “in” does not make the value it refers to immutable. While the function declaring the parameter cannot make changes to it, the value can be changed elsewhere. This doesn’t require multiple-threads, just a way to access the original variable the parameter refers to.
So, as your class isn't immutable, it can be changed elsewhere. This feature seems mostly about performance in passing the reference value around
Upvotes: 3