Sven van den Boogaart
Sven van den Boogaart

Reputation: 12331

c# Choosing Between Properties and Methods

After reading this microsoft article about when to use properties and methods, I'm a little bit confused.

At the example at the bottom they say:

The following code example shows a complete application that assumes that a property access is computationally inexpensive. The EmployeeData class incorrectly defines a property that returns a copy of an array.

specifically

The EmployeeData class incorrectly defines a property that returns a copy of an array.

What would be the right way to do it?

fiddle of the example code

Upvotes: 1

Views: 150

Answers (3)

dtell
dtell

Reputation: 2568

The section

use a method, rather than a property, in the following situations.

in the article you were reading tells you to use a method instead of a property of the property returns an array.

So the right way to do this would be creating a method to copy the array.

Upvotes: 0

user1023602
user1023602

Reputation:

The property is "incorrect" because the code inside it is slow.

public EmployeeRecord[] Employees
{
    get 
    {
        return CopyEmployeeRecords();   // slow code in property - bad
    }
}

Instead, write a method:

public EmployeeRecord[] Employees()
{
    return CopyEmployeeRecords();       // slow code in method - ok
}

Upvotes: 1

Philippe Paré
Philippe Paré

Reputation: 4418

This is just a guideline, but your properties should be as lightweight as possible. Copying an array, just like in the example, is quite expansive for a property. It should be a method. This way, anyone using this code knows it could take a bit of time. Properties usually reflect accessors for private fields, so people expect it to return almost immediately. Hope this makes sense.

Upvotes: 1

Related Questions