I have method overload issue, which I've asked about in a previous posting. After some feedback and research I'm convinced that I need to default some of the values being passed in my method.
My question is: is there a default value for the object datatype? If, so please provide an example.
Here is an example of a defaulted string
and int
parameter:
public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
For a copy of my code please see: OP
The only value you can use for the default value of an optional object
parameter is null
- or equivalently, default(object)
. There are no other compile-time constants of type object
. I'm slightly surprised that you can't use a string literal, given that string
is implicitly convertible to object
, but the compiler prevents that :(
Having said all of this, if you go behind the compiler's back you can do more than that... you can use DefaultParameterValueAttribute
and OptionalAttribute
to create optional parameters of type object
with string and numeric values. For example:
using System;
using System.Runtime.InteropServices;
class Test
{
static void Main(string[] args)
{
Foo(); // Prints 5 test
}
static void Foo([Optional, DefaultParameterValue(5)] object x,
[Optional, DefaultParameterValue("test")] object y)
{
Console.WriteLine("{0} {1}", x, y);
}
}
I'd advise against doing this though - it's somewhat against the spirit of things...
See more on this question at Stackoverflow