Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

.net - Elegant way to avoid NullReferenceException in C#

I want to do this

var path = HttpContext.Current.Request.ApplicationPath;

If any of the Properties along the way is null, i want path to be null, or "" would be better.

Is there an elegant way to do this without Ternaries?

ideally i would like this behavior (without the horrible performance and ugliness) string path;

try
{
    path = HttpContext.Current.Request.ApplicationPath;
}
catch
{
    path = null;
}

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[EDIT]

C# 6 got released a while ago and it shipped with null-propagating operator ?., which would simplify your case to:

var path = HttpContext?.Current?.Request?.ApplicationPath

For historical reasons, answer for previous language versions can be found below.


I guess you're looking for Groovy's safe dereferencing operator ?., and you're not the first. From the linked topic, the solution I personally like best is this one (that one looks quite nice too). Then you can just do:

var path = HttpContext.IfNotNull(x => x.Current).IfNotNull(x => x.Request).IfNotNull(x => x.ApplicationPath);

You can always shorten the function name a little bit. This will return null if any of the objects in the expression is null, ApplicationPath otherwise. For value types, you'd have to perform one null check at the end. Anyway, there's no other way so far, unless you want to check against null on every level.

Here's the extension method used above:

    public static class Extensions
    {
    // safe null-check.
    public static TOut IfNotNull<TIn, TOut>(this TIn v, Func<TIn, TOut> f) 
            where TIn : class  
            where TOut: class 
            { 
                    if (v == null) return null; 
                    return f(v); 
            }       
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...