Question

My code looks like this

static void SomeVoid(object obj1, object ojb2 = someDefaultValue) {
    // Do Something Here
}

the compiler says that Default parameter value for the 'obj2' must be a compile-time constant. what can I do ? someDefaultValue is string.Empty in my case.

Was it helpful?

Solution

Change parameter type to string, and use empty string instead:

static void SomeVoid(object obj1, string ojb2 = "") {
    // Do Something Here
}

Compiler is complaining, because default parameter value will be provided during compilation in place where your method is called. I.e. when you write

Foo.SomeVoid(42);

It would compile into

Foo.SomeVoid(42, ""); 

That's why default parameter value should be constant value. Also parameter type should be string, because all reference type parameters can be initialized with null constant only. And object is a reference type.


There is workaround for you. You can use parameter of object type with default value null and handle that value manually inside your method:

static void SomeVoid(object obj1, object obj2 = null) {

    if (obj2 == null)
        // use default value

    // Do Something Here
}

OTHER TIPS

You might just use a standard overload:

static void SomeVoid(object obj1) {
    SomeVoid(obj1, String.Empty);
}

static void SomeVoid(object obj1, object ojb2) {
    // Do Something Here
}

This also gives you the benefit that if you decide the default value shouldn't be String.Empty, you can change it without forcing callers to recompile to pass in the new default value. The other solutions have subtle differences in how they are called or behave; I think using an overload like this is the best way to ensure the exact same behaviour. (that said, if obj2 is supposed to be a string, I would totally go with @lazyberezovsky's answer)

You can not do that. The error message describes clearly: "A default parameter value of a reference type other than string can only be initialized with null".

And you can not use "" either.

I would simply go by:

static void SomeVoid(object obj1, object obj2 = null)
{
    obj2 = obj2 ?? "";
    // rest
}
static void SomeVoid(object obj1, object ojb2 = null) {
    ojb2 = ojb2 ?? someDefaultValue;

    // Do Something Here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top