Does it make sense to create an array property?

According to MSDN , methods should be used instead of properties when they return an array. They further discuss why this is the case with a concrete example.

However, there are a few cases where I see this seem a bit extreme.

CASE 1

The property is in the data container, and the rest of the data is properties. It is very unlikely that the property will ever be refactored to create a new array for each request.

public class Foo
{
    private readonly int[] bar;
    private int fooish;

    public Foo(int[] bar, int fooish)
    {
        this.bar = bar;
        this.fooish = fooish;
    }

    public int[] Bar
    {
        get { return bar; }
    }

    public int Fooish
    {
        get { return fooish; }
    }
}

CASE 2

Class public fields are reorganized into properties (at least provide the illusion of encapsulation).

public class Foo
{
    public int[] Bar { get; set; }
    public int Fooish { get; set; }

    // Other members...
}

My question is: is there any realistic argument for using them in methods if I know that they are supported by the field (and probably will always be)?

. , Java #, - , , ( Java , ). , - GetBar() SetBar(int[] bar), , ? .NET , ? ()

+4
1

-, , , - , , , .

, - , - ( ), .

IReadOnlyList<T>:

private int[] arr;
public IReadOnlyList<int> Arr { get { return arr; }}

, , , :

class MyClass
{
    private int[] arr;

    // can't clone the array, because your application requires the caller to change elements
    public int[] GetArr() { return arr; }
}

...

// very unclear for the caller that he actually modifying the array on the obj instance
int[] values = obj.GetArr();
values[2] = 12;

obj.Arr[2] = 12; .

+4
source

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


All Articles