Dimitri
Dimitri

Reputation: 2858

Cannot use object as a type of method's default parameter

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.

Upvotes: 3

Views: 2767

Answers (4)

radarbob
radarbob

Reputation: 5101

static void SomeVoid(object obj1, object ojb2 = null) {
    ojb2 = ojb2 ?? someDefaultValue;

    // Do Something Here
}

Upvotes: 1

Kaveh Shahbazian
Kaveh Shahbazian

Reputation: 13523

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
}

Upvotes: 1

Chris Sinclair
Chris Sinclair

Reputation: 23208

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)

Upvotes: 5

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236248

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
}

Upvotes: 5

Related Questions