2

I have a variable defined in one class, let's say class A:

private char[,] matrix;

Later in my code, this matrix is initialized and populated according to some conditions.

Now from another different class, let's say class B, I need to get the final matrix.

So I have two options:

  1. Implement a public property in class A that will be accessed from class B:

    public char[,] GetMatrix 
    { 
      get 
      { 
         if (this.matrix == null || this.matrix.Length == 0)
         {
            // Matrix is null or it has no elements on it.
            return null;
         }
         else
         {
            return this.matrix;
         }
      }
    }
    
  2. Implement a public method in class A that will be accessed from class B:

       public char[,] GetMatrix() 
        {  
             if (this.matrix == null || this.matrix.Length == 0)
             {
                // Matrix is null or it has no elements on it.
                return null;
             }
             else
             {
                return this.matrix;
             }
        }
    

As stated here it is recommended to use a method in case the operation returns an array.

Also it is said:

Use a method where the operation returns an array because to preserve the internal array, you would have to return a deep copy of the array, not a reference to the array used by the property. This fact, combined with the fact that developers use properties as though they were fields, can lead to very inefficient code

So in my case, which option is the best? and why?

Shiran Dror
  • 1,472
  • 1
  • 23
  • 36
Willy
  • 9,848
  • 22
  • 141
  • 284
  • C.) Prefer immutable types with well-defined contracts and avoid side-effects. – user2864740 Feb 25 '17 at 17:35
  • In properties, behind the scene, there are get and set methods that are called. – Nikhil Agrawal Feb 25 '17 at 17:37
  • In this case I'd argue the property is "better" (although the name is not following C# conventions) because it does not give the false impression of creating a new array (as the implementations are the same). The few cycles taken for the if-statement are likely inconsequential. Perhaps, an alternative wording of the question: "How much work is 'too much' to do in a Property getter?" – user2864740 Feb 25 '17 at 17:38
  • Specifically, the quote at the end is referring to an implementation that actually *does* create and return a new array (that's a different contract definition). In that case I would use a method for clarity of intent - not strictly for "performance". – user2864740 Feb 25 '17 at 17:42
  • @user2864740 what would be the correct property name? Matrix? – Willy Feb 25 '17 at 17:56
  • 1
    @user1624552 Something that avoids "Get". – user2864740 Feb 25 '17 at 19:12

0 Answers0