Let's say we have a method:
public void SomeMethod(out string[] someArray) { // ... }
Is there a way to do something similar to this:
IEnumerable<string> result;
SomeMethod(out result);
Edit: The point is, I dont' want to bind the out value to string[]
, I'd like the code to work even if the method declaration is changed to SomeMethod(out List<string> outputValue)
.
It's not allowed to change the type of an out parameter because type safety cannot be guaranteed. This is explained in detail in Eric Lippert's Blog.
Here is a code example how one could break type safety if it would be allowed:
IEnumerable<string> result;
public void Test()
{
SomeMethod(out result);
}
public void SomeMethod(out string[] someArray)
{
someArray = new string[];
ChangeTheType();
int n = someArray.Length; // BANG!! - someArray is now a List<string>
}
public void ChangeTheType()
{
result = new List<string>();
}
Obviously this is only a problem if result is not in the same scope as the call to SomeMethod but the compiler will not check for that. It is just not allowed.
Change the method signature to public void SomeMethod(out IEnumerable<string> someStrings)
. You can assign a string[]
to someStrings
inside SomeMethod
and if you later decide to use a List<string>
you can assign that also without braking the call.
Personally I would avoid out parameters in the first place: public string[] SomeMethod()
.
I'm sure it's not a best way, but you can write another method which do this job for you:
public class ClassA
{
private void SomeMethod(out IEnumerable<string> result)
{
string[] res;
SomeMethod(out res);
result = res;
}
public void SomeMethod(out string[] someArray)
{
someArray = new string[2];
}
void Test()
{
IEnumerable<string> result;
SomeMethod(out result);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With