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!
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!
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.
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).
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?
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);
}