Question

Difficult to explain in words, so I'll provide an example.

I want to output this in Razor (but it doesn't matter that it's razor, my question is about c#):

@SomeClass.SomeClass.SomeClass.ID.ToString()

Any of the SomeClass can be null (it's an external api which I don't really have influence on)

So I tried this:

@functions{
    private string Safe(Func<string> val, string defaultValue)
    {        
        try 
        {
            return val.Invoke();
        }
        catch(NullReferenceException ex)
        {
            return defaultValue;
        }
    }
}

And then this:

@Safe(SomeClass.SomeClass.SomeClass.ID.ToString, "value not found")

But no cigar ... Is there any way to achieve this? Thx.

UPDATE1: Using a NullReferenceException is obviously much beter.

Was it helpful?

Solution

You should pass the whole call:

@Safe(() => SomeClass.SomeClass.SomeClass.ID.ToString(), "value not found")

The reason you have to do it this way, is because now the exception will occur inside your method. Otherwise it will already throw a NullReferenceException before it can get to the ToString-method.

OTHER TIPS

I think you're pretty close. The problem here is that passing the ToString function requires that you be able to resolve ToString, which requires all of the objects in the chain to be non-null. Try passing a lambda in instead of the ToString function, which will defer that lookup until you try to evaluate it (inside the lambda):

@Safe(() => SomeClass.SomeClass.SomeClass.ID.ToString(), "value not found")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top