Search Unity

Feedback Mark native collections properties as readonly

Discussion in 'Scripting' started by RamType0, Dec 28, 2020.

  1. RamType0

    RamType0

    Joined:
    Sep 11, 2018
    Posts:
    67
    We need to dispose native collections(e.g. NativeArray<T>,NativeList<T>) when we finished to use them.
    And then, C# has language feature for this kind of context, "using".
    But currently, "using" doesn't work well for when we are writing into their properties..(CS1654 error appears)
    But in C#8 with Unity2020.2,we have solution for this issue.

    Code (CSharp):
    1.     struct NativeCollectionWithReadOnlyProperties :IDisposable
    2.     {
    3.         public int NonReadOnlyProperty
    4.         {
    5.             get => default;
    6.             set { }
    7.         }
    8.  
    9.         public readonly int ReadOnlyProperty
    10.         {
    11.             get => default;
    12.             set { }
    13.         }
    14.         public readonly int this[int i]
    15.         {
    16.             get => default;
    17.             set { }
    18.         }
    19.  
    20.         public readonly int Length
    21.         {
    22.             get => default;
    23.             set { }
    24.         }
    25.         public readonly int Capacity
    26.         {
    27.             get => default;
    28.             set { }
    29.         }
    30.         public void Dispose()
    31.         {
    32.            
    33.         }
    34.         public static void Sample()
    35.         {
    36.             using (var a = new NativeCollectionWithReadOnlyProperties())
    37.             {
    38.                 a.NonReadOnlyProperty = 0; //Error:CS1654
    39.                 a.ReadOnlyProperty = 0; //OK!
    40.                 a[0] = 0; // OK!
    41.                 a.Length = 0; // OK!
    42.                 a.Capacity = 0; // OK!
    43.             }
    44.         }
    45.     }
    By just marking their properties "readonly"!
    This will definitely improve usability of native collections.
    Please.