where TE...">

LINQ, output arguments, and "Using an unassigned local variable" error

I have a code similar to the following.

class MyClass<TEnum> where TEnum : struct
{
    public IEnumerable<TEnum> Roles { get; protected set; }

    public MyClass()
    {
        IEnumerable<string> roles = ... ;

        TEnum value;
        Roles = from r in roles
                where Enum.TryParse(r, out value)
                select value;   // <---- ERROR HERE!
    }
}

However, in the line above, I get an error:

Using an unassigned local variable 'value'

It seems to me that valueit will always be initialized in this case, since this parameter outis equal Enum.TryParse.

Is this a bug with the C # compiler?

+4
source share
2 answers

TL DR: The error says that the variable (presumably) is not assigned - FALSE. Reality, a variable is not necessarily assigned (using theoretical evidence available to the compiler).


LINQ ... , .

, :

roles.Where(r => Enum.TryParse(r, out value)).Select(r => value);

Enumerable.Select(Enumerable.Where(roles, r => Enum.TryParse(r, out value)), r => value);

LINQ -, ( , - ). , Where , , , TryParse .

.

:

bool flag = Blah();
int value;
if (flag) value = 5;
return flag? value: -1;

, , value, " ".

. " ", , "", .

+5

, .

Enum.TryParse(r, out value).

, roles ?

, CSC , roles - , .

, Enum.TryParse(r, out value) - value ?

.


() :

class MyClass<TEnum> where TEnum : struct
{
    public IEnumerable<TEnum> Roles { get; protected set; }

    public MyClass()
    {
        IEnumerable<string> roles = ... ;


        Roles = GetValues();   // <---- ERROR HERE!
    }

    public static IEnumerable<TEnum> GetValues(IEnumerable<String> roles)
    {       
        TEnum value; 
        String[] roleArray = roles.ToArray(); // To avoid the foreach loop.

        // What if roleArray.Length == 0?
        for(int i = 0; i < roleArray.Length; i++)
        {
             // We will never get here
             if (Enum.TryParse(roleArray[i], out value))
                 yield return value;
        }
    }
}

( ) - , Enum.TryParse(roleArray[i], out value) value.


LINQ.

Enumerable extensions, :

 TEnum value;
 Roles =  roles
     .Where(role => Enum.TryParse(role, out value))
     .Select(role => value);   <---- STILL ERROR HERE!

.

, value , , - Where () , , value , .

+6

All Articles