简体   繁体   中英

Default value for nullable value in c# 2.0

Using C# 2.0, I can specify a default parameter value like so:

static void Test([DefaultParameterValueAttribute(null)] String x) {}

Since this C# 4.0 syntax isn't available:

static void Test(String x = null) {}

So, is there a C# 2.0 equivalent for value types? For instance:

static void Test(int? x = null) {}

The following attempts don't compile.

// error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type
static void Test([DefaultParameterValueAttribute(null)] int? x) {}

// error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression
static void Test([DefaultParameterValueAttribute(new Nullable<int>())] int? x) {}

Unfortunately, the older versions of the C# compiler do not support this.

The C# 4.0 compiler compiles this:

public static void Foo(int? value = null)

Into:

public static void Foo([Optional, DefaultParameterValue(null)] int? value)

This is effectively the same as your first attempt (with OptionalAttribute added, in addition), which the C# 2 compiler errors on with CS1908, as this wasn't supported directly in that version of the compiler.

If you need to support C# 2, in this case, I would recommend adding an overloaded method instead:

static void Test()
{
    Test(null);
}
static void Test(int? x)
{
    // ..

Reed is of course correct; I just thought I'd add an interesting fact about a corner case. In C# 4.0 you can say: (for struct type S)

void M1(S x = default(S)) {}
void M2(S? x = null) {}
void M3(S? x = default(S?)) {}

But oddly enough you cannot say

void M4(S? x = default(S)) {}

In the first three cases we can simple emit metadata that says "the optional value is the default value of the formal parameter type". But in the fourth case, the optional value is the default value of a different type . There is not an obvious way to encode that kind of fact into metadata. Rather than coming up with a consistent rule across languages for how to encode such a fact, we simply made it illegal in C#. It's likely a rare corner case, so no great loss.

Apparently you can't use this attribute.

As you know attribute parameters are 'serialized' to metadata at compile time - so you need constant expression. Since the compiler doesn't like 'null' you're out of options.

What you can do is - overload - define another Text method with no parameters which calls your Text method with null

Does this work: [DefaultParameterValueAttribute((int?)null)] ? Tried - this doesn't work too (

我相信它应该是:

static void Text(int? x = default(int?));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM