lundi 3 avril 2017

Check if method is accessing collection

Situation:

I am stuck in c# 5.0, I cannot upgrade to c# 6.0 in my current environment until after 2020. Meanwhile the null checks in the codebase have gotten incredibly long, and sometimes properties that are being accessed are not being checked for null before being accessed. A while ago I created a TemporaryLanguageFeatures class that contains some facsimiles of C# 6.0 behavior like nameof. I have decided to create a NullPropagation method that takes an Expression<Func<T>> and checks each for null before moving on to the next object in the series.

Problem:

When the expression includes access to a collection and the collection is empty or the index is out of range of the collection, I get the related empty collection or Index out of range error. I have access to the expression, the LambdaExpression created, and the compiled delegate/its MethodInfo.

Without a try/catch I need to check if the given call would produce an error for being:

A) index out of range (collection has 10 members, expression is as follows):

var answer = NullPropagation(() => item.Location.PhoneNumbers[500]);

B) The collection being empty (collection has no members, expression is as follows):

var answer = NullPropagation(() => item.Location.PhoneNumbers.First());

Current Code:

var members = new List<Expression>();

...Fill the collection, etc.

var previousMethod = (MethodInfo) null;
var nullFound = members.Any(x => 
{
    if (previousMethod != null && typeof(IEnumerable).IsAssignableFrom(previousMethod.ReturnType)) 
    {
        Console.WriteLine("HIT!");
        //Todo: Detect collection empty/index out of range, return true;
    }
    previousMethod = method;
    return Expression.Lambda(x).Compile().DynamicInvoke() == null;
}
...





Aucun commentaire:

Enregistrer un commentaire