Rey
Rey

Reputation: 4000

An expression tree may not contain an out argument variable declaration

I am using c# 7.3 with new feature to create a generic method where the type should be an enum.

I have a method like this:

public static bool TryConvertToEnum<T>(this int value, out T returnedValue) 
    where T : struct, Enum
{  
    if (Enum.IsDefined(typeof(T), value))
    {
        returnedValue = (T)Enum.ToObject(typeof(T), value);
        return true;
    }

    returnedValue = default;
    return false;
}

It will try to convert an int to a specific enum. I am trying to use this method in two cases. One does work while the other case doesn't.

Here is the working example:

if (documentTypeId.TryConvertToEnum(out DocumentType returnedValue)
    && returnedValue == DocumentType.Folder)
{
    //In this case it works fine
}

If I try to use this in a select method it does not work:

var comments = await DatabaseService.GetAll(filter)
    .OrderByDescending(x => x.Id)
    .ToPaginated(page)
    .Select(x => new PostCommentViewModel
    {
        Id = x.Id,
        Status = x.Status.TryConvertToEnum(out PostCommentStatusType returnedValue) ?
            returnedValue : PostCommentStatusType.None //Here it does not work
    }).ToListAsync();

In the second case it does not allow the project to be build. It gives the error:

An expression tree may not contain an out argument variable declaration

When I hover, RSharper does show a popup stating: Expression tree may not contain an out argument variable declaration

I am little confused to the part may, not sure if expression tree can have or not out params...

Does anybody have any idea why this happens ?

Upvotes: 4

Views: 7704

Answers (1)

Rey
Rey

Reputation: 4000

It seemed to be an easy fix actually. I only had to materialize data before applying select function :(palmhand).

var comments = DatabaseService.GetAll(filter)
    .OrderByDescending(x => x.Id)
    .ToPaginated(page)
    .ToList()//Applied ToList here
    .Select(x => new PostCommentViewModel
    {
        Id = x.Id,
        Comment = x.Comment,
        Created = x.Created,
        Name = x.Name,
        ParentId = x.ParentId,
        PostId = x.PostId,
        Status = x.Status.TryConvertToEnum(out PostCommentStatusType returnedValue) ?
            returnedValue : PostCommentStatusType.None 
    }).ToList(); 

Upvotes: 3

Related Questions