Arrays as properties and indexers

I have two private arrays in a class that starts a specific operation using a method. After calling this method, these two arrays are filled with results. It is not a good practice to create these array properties, so I planned to have a separate property that returns a clone of a private array.

1) What is the overhead of returning the clone array? Is it inconspicuous in every case?

2) I could use an index if there was only one array. Is there a special mechanism for using indexers for multiple arrays in a class?

+4
source share
3 answers

I think you mean "overhead" or "cost", not "overload." In any case, it is computationally O(1) , so it depends on the size of the thra rray, but generally speaking, copying Array is a cheap operation if it is under a thousand elements or so.

If you do not plan to modify arrays, you can open your private arrays by wrapping them in ReadOnlyCollection<T> as follows:

 private TWhatever[] _array; public ReadOnlyCollection<TWhatever> Elements { get; private set; } public ClassConstructor() { _array = new TWhatever[1000]; this.Elements = new ReadOnlyCollection<TWhatever>( _array ); } 
+3
source

Cloning an array is a memory allocation; the effect will depend directly on the size of the array.

An indexer is just a method; Another approach could be to simply add a method such as GetName(int index) and GetValue(int index) (if, for example, your arrays are names / values). C # has no built-in named indexers.

If performance is important and you need to access multiple values, then another approach is to have a method that copies the values ​​to the array that the calling object provides, for example GetNames(string[] names, int offset) { this.names.CopyTo(names, offset); } GetNames(string[] names, int offset) { this.names.CopyTo(names, offset); } . This can be useful by allowing the caller to allocate one buffer and then use it to get values ​​from several objects - or if you add several parameters (for a counter, etc.) to get values ​​in batches, and not separately. However, this is necessary / useful, depending on the specific scenario.

+2
source

Maybe it's possible to do something like this

 KeyValuePair this[int i] { get { /* code */ } private set{ /* code */ } } 
+1
source

Source: https://habr.com/ru/post/1438367/


All Articles