tags:

views:

21

answers:

1
static class MyClass
{
    static void Main()
    {
        bool b1 = false;
        if ( b1 )
        {
            throw new MyException(GetText(b1));
        }
    }

    public static string GetText(bool bFlag)
    {
        if ( bFlag==false )
        {
            throw new Exception("'GetText' method should not be called when condition is 'false');
        }
        return "Some error text";
    }
}

All works fine in example above (I mean when condition b1 is 'True' then 'MyException' will be generated with a proper text. And when condition if 'False' then nothing will be happened

I want to have some helper method for my exception class:

class MyException : Exception
{
    public void FailIfTrue(bool bCondition, string strErrorMessage)
    {
        if ( bCondition )
        {
            throw new Exception(strErrorMessage);
        }
    }
}

In this case "Main" method would be changed to another one:

static class MyClass
{
    static void Main()
    {
        bool b1 = false;
        MyException.FailIfTrue(
            b1, 
            GetText(b1)
            );
    }
}

In this case 'GetText' method will be called...

Question:

Do you see any good workaround or solution to create a helper that will call 'GetText' only when it's result is required inside of 'FailIfTrue' function?

Any thoughts are welcome.

Thank you.

+2  A: 

Actually, I see a workaround (pass not a string parameter, but a Func):

public void FailIfTrue(bool bCondition, Func<string> funcErrorMessage)
{
    if ( bCondition )
    {
        throw new Exception(funcErrorMessage());
    }
}

But not sure if it is the best what is possible here.

Please advise!

Budda
Yes, passing in a delegate to be executed only in certain situations is a good way of deferring execution.
Jon Skeet