Sreedhar
Sreedhar

Reputation: 30025

Creating Macro's in C#

Is there a way to create macros in c#

ex:

string checkString = "'bob' == 'bobthebuilder'" (this will be dynamic)

if (@@checkString) //......... else //.........

Thanks

Upvotes: 3

Views: 5471

Answers (4)

Marc Bollinger
Marc Bollinger

Reputation: 3119

As mentioned, no, but there are a number of other approaches:

  • Conditional compilation via #if
  • Templating via T4 or something else (we use a port of Ned Batchelder's (mentioned) Cog
  • Aspect-Oriented Programming via something like PostSharp
  • As Jon said, lots of ways; it'd be better to describe exactly what you want to do.

Upvotes: 1

user166390
user166390

Reputation:

T4 seems to be gaining traction these days for .NET work. It's not quite what you asked for, but it may be extremely beneficial in some cases (or it may just be a hint down the wrong path).

In most cases, esp. with generics, I do not wish for 'templates' or 'macros' in C# (or Scala). In the example above, you could simply use:

bool sameStuff = "'bob' == 'bobthebuilder'";
...
if (sameStuff) {
  ...
}

More complex cases can generally be dealt with refactoring methods or using anonymous functions.

Additionally, attributes (while a completely different approach) round out the case for many "traditional" uses of templates.

Upvotes: 1

leppie
leppie

Reputation: 117220

Short answer: No.

Long answer: You can write a wrapper around the C/C++ compiler's preprocessor.

Most of the syntax will be accepted with the notable exception of #region/#endregion. You can just prefix those with #pragma before processing, and remove the #pragma part afterwards.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500475

No, C# doesn't have macros. You could capture your logic in a delegate and apply that delegate in multiple places, potentially... would that help?

If you could describe the problem you're trying to solve rather than the solution you think you'd like, we may be able to help more.

Upvotes: 2

Related Questions