How do I default a parameter to DateTime.MaxValue in C#?

I wish to say:

public void Problem(DateTime optional = DateTime.MaxValue)
{
}

But the compiler complains that DateTime.MaxValue is not a compile time constant.

DateTime.MinValue is easy, just use default(DateTime)

see also "How do I default a parameter to Guid.Empty in C#?"

I do not wish to use method overloading, as the method I am trying to tame has 101 parameters!


我会用这个替代这样的东西:

public void Problem(DateTime? optional = null)
{
   DateTime dateTime = optional != null ? optional.Value : DateTime.MaxValue;
   // Now use dateTime
}

According to one of your comments, you are trying to make a method with 101 parameters more usable for the callers.
I strongly suggest, that you create a parameter class and initialize the properties of that class with the default values. Provide an overload for your method that accepts only one parameter: The parameter class.
This will really improve the usage of your method, because the user can even reuse its parameter class instance if he needs to change only one parameter.


What you're asking to do is simply not possible. DateTime.MaxValue is not a compile-time constant; it's actually a read-only field that is initialized at runtime by a static constructor. That difference becomes quite critical here. Optional parameters require compile-time constants, as they bake the value directly into the code.

However, the real problem is that your method takes 101 parameters. I've never seen anything crying out so loudly for refactoring. My recommendation would be change your method to accept an instance of a class, instead. That will also give you more flexibility in specifying default values for individual properties of the class. In particular, you'll be able to specify values that are not compile-time constants.

链接地址: http://www.djcxy.com/p/21228.html

上一篇: 为什么不能在类中声明const静态字符串

下一篇: 如何在C#中将参数默认为DateTime.MaxValue?