C# – syntactic sugar C# property syntax to instantiate generic collections

cpropertiessyntax

The following program will fail because Contracts is not instantiated.

Of course I can instantiate it in my constructor but if I have dozens of properties and/or multiple constructors I have to keep track of which are instantiated, etc.

And of course I could create large blocks for these properties with full gets and sets and private field variables, etc. But this gets messy as well.

Isn't there a way to automatically instantiate these collections with the nice C# property syntax?

using System;
using System.Collections.Generic;

namespace TestProperty232
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            customer.FirstName = "Jim";
            customer.LastName = "Smith";

            Contract contract = new Contract();
            contract.Title = "First Contract";

            customer.Contracts.Add(contract);

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public List<Contract> Contracts { get; set; }

        public Customer()
        {
            //Contracts = new List<Contract>();
        }
    }

    public class Contract
    {
        public string Title { get; set; }
    }
}

Best Answer

There is no such syntactic sugar, but I'd like to point out a few things:

  • Collection properties should be read-only in any case.
  • If you have a lot of such properties in a single type, it's a strong symptom that you are violating the Single Responsibility Principle
  • If you have multiple constructors, you should always take great care that there's only one constructor that does the real work, and all other constructors delegate to that constructor. Alternatively you can delegate all constructor work to a private Initialize method.
Related Topic