views:

1909

answers:

5

Hi!

Is C# able to define Macros like in C with Preprocessor statements to ease regular typing of certain repeating statements like Console.WriteLine("foo"); ?

I didn't find a solution.

Thanks!

+6  A: 

No, C# does not support preprocessor macros like C. Visual Studio on the other hand has snippets. Visual Studio's snippets are a feature of the IDE and are expanded in the editor rather than replaced in the code on compilation by a preprocessor.

Andrew Hare
+3  A: 

Luckily, C# has no C/C++-style preprocessor - only conditional compilation and pragmas (and possibly something else I cannot recall) are supported. Unfortunatelly, C# has no metaprogramming capabilities (this may actually relate to your question to some extent).

Anton Gogolev
A: 

Turn the C Macro into a C# static method in a class.

Robert
A: 

How would one address this problem:

for (some arbitrary number of times) { try { (one of several arbitrary calls to web service that needs retries, with arbitrary return types) } catch (Exception e) { // Done with retries? Throw real exception; otherwise, try again } }

I want to surround the arbitrary text with something that will do a retry without replicating the loop/try/catch code many times. Because the number of args to the service and the returns vary widely, a delegate doesn't seem like the answer. Then again, I'm fairly new to C# - is there a clever way to do this?

Dana
+1  A: 

I eventually found a solution in .NET 3.5, which I liked. I use a static method, called from a lambda expression:

TryWithRetries(() => result = MyThing.MyMethod([appropriate args]), retries, timeout); 

public static void TryWithRetries(Action clientCall, uint retries, int retryTimeout)
{
do
{
    try
    {
        clientCall();     // Entire Action, including any setting of a local variable to return value and parameters
        break;
    }
    catch (Exception e)
    {
        if (retries > 0)
        {
            System.Threading.Thread.Sleep(retryTimeout);
            retryTimeout *= 2;
        }
        else
        {
            throw e;
        }
    }
} while (retries-- > 0);
}
Dana