문제

So, the title is a bit misleading and I'll sort it out first.

Consider the following piece of code:

public static ADescription CreateDescription(string file, string name, params string[] othername)
{
    return new ADescription(file, name, othername.ToList<string>());
}

This will throw a System.ArgumentNullException in a case where the user deliberately enters a null at the end. For e.g.:

ADescription.CreateDescription("file", "name", null); // example

Now I have a property that basically gets & sets the othername list. My concern is that I will have to check at every stage like (in the property, as well as in this method):

if (othername == null){
   // do nothing
}
else{
    othername.ToList<string>; // for example
}

because, null is acceptable for othername. Is there any way that c# natively provides this capability where if othername is null, then it wouldn't really operate ToList() on that.

도움이 되었습니까?

해결책

You can use a ternary operator:

 return new ADescription(file, name, othername==null?null:othername.ToList<string>());

Or create an extension method as described in the accepted response here Possible pitfalls of using this (extension method based) shorthand:

public static class IfNotNullExtensionMethod
{
    public static U IfNotNull<T, U>(this T t, Func<T, U> fn)
    {
        return t != null ? fn(t) : default(U);
    }
}

Your code would be:

return new ADescription(file, name, othername.IfNotNull(on => on.ToList());

다른 팁

You could make an extension method to handle this:

public static class MyExtensionMethods
{
    public static List<T> ToListIfNotNull<T>(this IEnumerable<T> enumerable)
    {
        return (enumerable != null ? new List<T>(enumerable) : null);
    }
}

Then you can substitute the extension method wherever you would otherwise use ToList().

return new ADescription(file, name, othername.ToListIfNotNull());
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top