Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Only set property when value is given

I have a class with a full prop and the default value is already set

I was wondering if there was a way of only setting the value of the property if a value with given when crate a new instance of this class?

    public DateTime dStart { get; set; }
    private DateTime _dStop;

    public DateTime dStop
    {
        get { return _dStop; }
        set { _dStop = DateTime.Today; }
    }

    public UserControl1(DateTime dateStart, DateTime dateEnd)
    {
        // 
        InitializeComponent();
    }

Creating an Instance of the class

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

XtraForm test = new UserControl1(dateStart, optional Property);

>Solution :

Make it nullable, and set it = null in the parameter list. this makes it optional, and all optional parameters must always go at the end of the list.

public DateTime dStart { get; set; }
private DateTime _dStop;

public DateTime dStop
{
    get { return _dStop; }
    set { _dStop = DateTime.Today; }
}

public UserControl1(DateTime dateStart, DateTime? dateEnd = null)
{
    if (dateEnd.HasValue)
        _dStop = dateEnd.Value;
    InitializeComponent();
}

Usage:

  1. XtraForm test = new UserControl1(dateStart)
  2. XtraForm test = new UserControl1(dateStart, dateEnd)
  3. XtraForm test = new UserControl1(dateStart, dateEnd: dateEnd)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading