Can I use the result of a C# method (with an argument) as a default argument of another?

c#, static-methods

Solution

You can't do this. From the spec:

A default value must be one of the following types of expressions:

a constant expression;

an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;

an expression of the form default(ValType), where ValType is a value type.

If you'd tried your `CreateFooItem(fooResult = GetFooBar(int foo))` example, you'd have got the compiler error "Default parameter value for 'fooResult' must be a compile-time constant" which is a shorter version of the above.

Problem

I have a static class with method: ``` public static class FooUtilities { public static FooStruct[] GetFooBar(int foo) { var fooStruct = new FooStruct[]; // Connect to SOAP API, collect data to put in fooStruct ... return fooStruct; } } ``` Now I want to use the result of GetFooBar(int foo) as an argument to another method that uses the results of this method to create new fooItem items, something like: ``` public static FooItem CreateFooItem(fooResult = GetFooBar(int foo)) { var fooItem = new FooItem(fooResult[0].value, fooResult[1].value,fooResult[2].value); ... return fooItem; } ``` The way I do it now is to write this: ``` public static FooItem CreateFooItem(FooStruct[] fooResult) { var fooItem = new FooItem(fooResult[0].value, fooResult[1].value,fooResult[2].value); ... return fooItem; } ``` This works, but then I have to call the method like: ``` FooItem myItem = FooUtilities.CreateFooItem(FooUtilities.GetFooBar(12321)); ``` What I'd like is to be able to call: ``` FooItem myItem = FooUtilities.CreateFooItem(); ``` And have the argument included implicitly when this method is called. Is this possible?

Original source