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
}