Joy
Joy

Reputation: 7028

Check for null using generic delegate parameters with param keyword

I have a interesting case here . I have a method call as

bool pass= Check.CheckNotNull<RemoveRoleFromUserCommand>(x => x.RoleName, x => x.UserId);

Now I want to Make this method definition as something like this ..

public static void CheckNotNull<T>(params Expression<Func<T, object>>[] @params)
    {
        return @params.All(x=> ..... );
    }

How to check for all of the values in @params delegate for all values that I have passed.

Upvotes: 0

Views: 103

Answers (1)

dcastro
dcastro

Reputation: 68670

Well, if you want to invoke the delegates, you need an instance of T. So add that as an argument.

public static bool CheckNotNull<T>(T item, params Func<T, object>[] @params)
{
    return @params.All(selector => selector(item) != null );
}

In response to the comment:

public static bool CheckNotNull<T>(T item, params Func<T, object>[] @params)
{
    return @params.All(selector =>
        {
            var selected = selector(item);
            return selected is string? string.IsNullOrEmpty(selected as string) : selected != null;
        } );
}

Upvotes: 3

Related Questions