Frage

Good day all.
I am working on something that handles tasks.
Each task consists of 3 strings and a DateTime Object

Below is the constructor I built.

public Task(string von, string was, string an, DateTime zeit = DateTime.Now)

When compiling I get compiler error

Default parameter value for 'zeit' must be a compile-time constant (CS1736)

I assume the problem is, that -obvioulsy- the value for DateTime.Now depends on the time the constructor is called, which is the whole point that I want to have here.

I already looked at [this] thread, but it does not really apply to me, because the memory demand for a DateTime Object is always the same and that thread says the problem is the unknown heap-demand of that call.1
I already have an idea for a work-around (see below), but as we all know work-arounds are not best practice

public Task(string von, string was, string an, DateTime zeit){
    if(zeit == null)
        dateOfCreation = DateTime.Now; //dateOfCreation being the name of Task's internal DateTime field.
    else
        dateOfCretion = zeit;

So if I want to use the current DateTime I pass null. However: If I take the time and effort to always specifically pass null, I might as well each time pass DateTime.Now.

Question: Is there a way to get parameter DateTime zeit = DateTime.Now accepted or substituted with identical outcome?

War es hilfreich?

Lösung

Use Constructor overloading instead:

public Task(string von, string was, string an, DateTime zeit)
{
 ...
}

public Task(string von, string was, string an) : this(von, was, an, DateTime.Now)
{
  ...
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top