Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on Dec 8, 2022, between 7 am & 7 pm EST, in the DOTS Dev Blitz Day 2022 - Q&A forum, Discord, and Unity3D Subreddit to learn more about DOTS directly from the Unity Developers.
    Dismiss Notice
  3. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Feedback Mark native collections properties as readonly

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

  1. RamType0

    RamType0

    Joined:
    Sep 11, 2018
    Posts:
    57
    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.