/
SynchronizedFieldAssignment.CSharp8.cs
43 lines (35 loc) · 1.52 KB
/
SynchronizedFieldAssignment.CSharp8.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
class Test
{
static readonly object staticReadonlyField = null;
static object staticReadWriteField = null;
readonly object readonlyField = null;
object readWriteField = null;
Test()
{
ref object refToReadonlyField = ref readonlyField;
lock (refToReadonlyField) { } // Noncompliant, while the reference is to a readonly field, the reference itself is a local variable and as of C# 7.3 can be ref reassigned
ref object refToReadWriteField = ref readWriteField;
lock (refToReadWriteField) { } // Noncompliant
}
void ReadonlyReferences()
{
lock (RefReturnReadonlyField(this)) { }
lock (RefReturnStaticReadonlyField()) { }
lock (StaticRefReturnReadonlyField(this)) { }
lock (StaticRefReturnStaticReadonlyField()) { }
ref readonly object RefReturnReadonlyField(Test instance) => ref instance.readonlyField;
ref readonly object RefReturnStaticReadonlyField() => ref Test.staticReadonlyField;
static ref readonly object StaticRefReturnReadonlyField(Test instance) => ref instance.readonlyField;
static ref readonly object StaticRefReturnStaticReadonlyField() => ref Test.staticReadonlyField;
}
void OnANewInstanceOnStack()
{
lock (stackalloc int[] { }) { } // Error [CS0185]
lock (stackalloc [] { 1 }) { } // Error [CS0185]
}
void CoalescingAssignment(object oPar)
{
lock (oPar ??= readonlyField) { } // FN, null conditional assignment not supported
}
}