Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Accessors and Collections

Tags:

c#

collections

When defining classes I expose class members as properties along the lines of :

class ClassA
{
    private String _Name;

    public String Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
 }

What is best practice for dealing with collections within classes, with respect to accessors

So if the class is extended to something like :

class ClassA
{
    private String _Name;
    private List<String> _Parts = new List<String>();

    public String Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
 }

How do I expose the next item?

like image 962
BENBUN Coder Avatar asked Feb 26 '23 12:02

BENBUN Coder


2 Answers

Expose a read-only instance of the collection. Note that the contents are not read-only, but the reference is.

public IList<String> Parts { get; private set; }
like image 142
Phil Hunt Avatar answered Mar 07 '23 08:03

Phil Hunt


The naming conventions I've come across recommend

private String _name;

Also you could use automatic properties which generate the same code you've written

public string Name {get; set;}

For collections, I don't like to expose the actual collection but methods to work on it.

public void Add(...
public void Remove(...

Otherwise you could make it readonly with an automatic property

public IList<string> Parts {get; private set;}
like image 40
Yuriy Faktorovich Avatar answered Mar 07 '23 09:03

Yuriy Faktorovich