Home > Back-end >  C# Only set property when value is given
C# Only set property when value is given

Time:03-22

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

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

CodePudding user response:

You could make it a private set so that it can only be initialized via the constructor or exposing a method of the class to set it, which it doesn't sound like you want to, then add an extra constructor which only takes the DateTime start:

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

public DateTime dStop
{
    get { return _dStop; }
    private set { _dStop = value; }
}

public UserControl1(DateTime dateStart, DateTime dateEnd)
{
    //value was given, so set it
    dStop = dateEnd;
    // 
    InitializeComponent();
}

public UserControl1(DateTime dateStart)
{
    //in this instance you set it to some default value as the value was not given
    dStop = DateTime.Today;
    // 
    InitializeComponent();
}

CodePudding user response:

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)
  •  Tags:  
  • c#
  • Related