Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an out parameter of string[] as IEnumerable<string>

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).

like image 294
hattenn Avatar asked Jan 14 '23 06:01

hattenn


2 Answers

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().

like image 128
pescolino Avatar answered Jan 22 '23 03:01

pescolino


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);
        }
    }
like image 37
Alexander A. Sharygin Avatar answered Jan 22 '23 02:01

Alexander A. Sharygin