Elisabeth
Elisabeth

Reputation: 21206

Instantiate the field of an Automatic propertiy automatically in C#

this is my Model:

public class Schoolclass
{
    private List<Pupil> _pupils;

    public Schoolclass()
    {
        _pupils = new List<Pupil>();
    }            

    public int SchoolclassId { get; set; }
    public string SchoolclassCode { get; set; }


    public List<Pupil> Pupils
    {
        get { return _pupils;} 
        set { _pupils = value; }
    }        
} 

Can I do this somehow with C# only without 3rd-party tools:

[Initialize]
public List<Pupil> Pupils {get;set}

I want that C# generates the field _pupils automatically.

Upvotes: 2

Views: 500

Answers (1)

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158289

There is no automatic way, but you can still assign the property in the constructor:

public Schoolclass()
{
    Pupils = new List<Pupil>();
}   

Also, since Pupils is a collection, I would suggest making it read-only:

public List<Pupil> Pupils {get; private set;}

Update
Full class would look like so:

public class Schoolclass
{
    public Schoolclass()
    {
        Pupils = new List<Pupil>();
    }            

    public int SchoolclassId { get; set; }
    public string SchoolclassCode { get; set; }
    public List<Pupil> Pupils { get; private set; }

} 

Upvotes: 8

Related Questions