Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# anonymous method in a if statement?

In c#, can I write something like this :

if (
     (
            try {
                ...
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
     ) == true
   )
{
...
}

without having to move all my try/catch block inside a new function

-- edit --

OK. I complete my question. (and maybe answer it a bit). What is supposed to be in the try/catch is a kind of XmlDocument.TryLoad(stream) (like there's a int.tryParse(string)). I'll need it only once so that's why I'd wanted to avoid making an extra func. So my code would be something like

            try {
                new XmlDocument().Load(foo);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

I just want to know if it goes wrong. I don't care the reason (stream empty, bad encoding).

There are a lot of interesting answers but I think what's the more appropriate for me is to create a extension method for xmlDocument. It will be way cleaner (and reusable and easier to read) than trying to force an anonymous method in my statement

like image 745
frenchone Avatar asked Feb 22 '26 01:02

frenchone


1 Answers

You can't use that exact syntax, no. You could write:

Func<bool> func = () =>
{
    // Code in here
};

if (func())
{
    ...
}

... but personally I'd extract it into a separate method. It's likely to be considerably more readable - and potentially easier to test, too.

like image 51
Jon Skeet Avatar answered Feb 23 '26 16:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!