Hans Rudel
Hans Rudel

Reputation: 3611

c# returning arrays via properties

Id like to firstly apologise for what may appear to be a stupid question but im confused regarding the following.

Im writting a class library which will not be running on the UI thread. Inside the CL i need an array which im going populate with data received from a stored procedure call. I then need to pass this data back to the UI thread via an event.

Originally i was going to write the following.

public class ColumnInformation
{
    public string[] columnHeaderNames;
    public string[] columnDataTypes;
}

but im pretty sure that would be frowned upon and i instead should be using properties.

public class ColumnInformation
{
    public string[] columnHeaderNames {get; set;}
    public string[] columnDataTypes {get; set;}
}

but then i came across the following. MSDN

so am i correct in assuming that i should actually declare this as follows:

public class ColumnInformation    
{        
    private string[] _columnHeaderNames;         

    public Names(string[] headerNames)        
    {            
        _columnHeaderNames = headerNames;        
    }         

    public string[] GetNames()        
    {            
        // Need to return a clone of the array so that consumers            
        // of this library cannot change its contents            
        return (string[])_columnHeaderNames.Clone();        
    }    
}

Thanks for your time.

Upvotes: 0

Views: 1077

Answers (1)

Tilak
Tilak

Reputation: 30728

If your concern is the guideline CA1819: Properties should not return arrays,
It will be same whether you are exposing Array as a Public Field, or Property (making readonly does not matter here). Once your original Array is exposed, its content can be modified.

To avoid this, as the link suggest, make Field private, and return Clone from the Getter. However major concern is that there may be multiple copies of your array if retrieved many times. It is not good for performance and synchronization.

Better solution is ReadOnlyCollection.

Using ReadOnlyCollection, you can expose the collection as read only which cannot be modified. Also any changes to underlying collection will be reflected.

Upvotes: 1

Related Questions