pQuestions123
pQuestions123

Reputation: 4611

c# Default datetime? method parameter where nulls mean something

I have a method with a bunch of defaulted datetime? parameters. I would like to be able to process nulls. I mean, if a caller passes in a null, I would like to process it as well.

So, I don't want to write:

public void MethodName(DateTime? signedConsent2 = null) {
}

I tried:

public void MethodName(DateTime? signedConsent2 = (DateTime?)default(DateTime)) {
}

but I am getting "The default parameter must be a compile time constant".

First off, I don't understand why default(DateTime) is a compile time constant but (DateTime?)default(DateTime) is not. Second off, is there any solution for this problem aside form overloading methods (which would be a lot of work since I have so many arguments).

Thanks in advance.

Upvotes: 0

Views: 271

Answers (3)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You'll need two overloads of your method:

public void MethodName()
{
    MethodName(default(DateTime));
}

public void MethodName(DateTime? signedConsent2)
{

}

Upvotes: 3

Habib
Habib

Reputation: 223267

I believe you are looking to handle multiple scenarios. Like calling the method as:

MethodName();
MethodName(null); //or MethodName(default(DateTime?));

Where calling it without parameter means something different than call it with null or DateTime? value.

In that case You have no other option but to define two overloads. You can't handle that with default parameter. There is no way for you to know whether method is called without a parameter or with a valid DateTime? parameter holding null value. In either case you will end up with null in your parameter.

public void MethodName()
{
    //Method without any parameter called
    MethodName(default(DateTime?));// call overload
}
public void MethodName(DateTime? signedConsent2 = default(DateTime?))
{
}

or public void MethodName(DateTime? signedConsent2 = null)

For:

First off, I don't understand why default(DateTime) is a compile time constant but (DateTime?)default(DateTime) is not.

The second code (DateTime?)default(DateTime) is doing an explicit cast which is a runtime operation and hence the error.

Upvotes: 2

n8wrl
n8wrl

Reputation: 19765

I would declare the parameters like you did at first:

public void MethodName(DateTime? signedConsent2 = null) {
}

and then when it's time to use them, coalesce the default:

var x = signedConsent2 ?? default(DateTime);

One advantage to this is, you may change your defaults, and you won't have to change the method signature. That's a good thing.

Upvotes: 0

Related Questions