Skip to content

The property of Struct Record should add [<IsReadOnly>] for the read operation #8962

@RealmPlume

Description

@RealmPlume

I just read the article https://docs.microsoft.com/en-us/dotnet/csharp/write-safe-efficient-code,
and checked. I see that when I use C # to write the following code:

    struct Bar
    {
        public int Item1 { get; set;}
        public int Item2 { get; set;}
    }

Actually Item1 is compiled as:

public int Item1
{
	[IsReadOnly]
	[CompilerGenerated]
	get
	{
		return <Item1>k__BackingField;
	}
	[CompilerGenerated]
	set
	{
		<Item1>k__BackingField = value;
	}
}

See, It adds a [IsReadOnly] attribute in front. So, I think it can be recognized and optimized by the C # compiler when it is passed as a parameter.

But if I write F # code like this:

[<Struct>]
type Bar = {
    Value: int
    mutable Text: string
}

compiled as:

[CompilationMapping(SourceConstructFlags.Field, 1)]
public string Text
{
	get
	{
		return Text@;
	}
	set
	{
		Text@ = value;
	}
}
[CompilationMapping(SourceConstructFlags.Field, 0)]
public int Value
{
	get
	{
		return Value@;
	}
	set
	{
		Value@ = value;
	}
}

Neither Value nor Text adds the [IsReadOnly] attribute above get.
Now if I pass the record to a C # function as readonly mode, even if I only do a read operation, the ldobj instruction will be generated.

But C # struct will not.

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions