Kobek
Kobek

Reputation: 1211

#define preprocessor in c#

I am coming from a C++ background, trying to learn C#.

I find it really annoying, that every time I wish to print something to the console I have to type something like Console.WriteLine("whatever");

If I was using C++ I would just define something like print(x) with a #define, but in C# I can't get it working.

My code is like this:

#define print(x) Console.WriteLine(x);

The issue is that C# wants me to keep it at the top of my code, before I have included my "using system" headers. Thus, the compiler does not know what Console or WriteLine() are. If I put it below this, I get an error telling me I need to have my preprocessor at the top.

Can someone help me out and tell me how I could get around this issue.

Upvotes: 0

Views: 1434

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180977

No such luck as preprocessor macros to abbreviate, but in C#6 you can use using static to make the calls slightly less verbose;

using static System.Console;

namespace TestConsole
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            WriteLine ("Test");    // Uses Console.WriteLine
        } 
    }
}

...and - of course - you can use it to get your print function;

using static Utility;

static class Utility {
    public static void print(string format, params object[] parms) {
        System.Console.WriteLine (format, parms);
    }
}

namespace TestConsole
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            print ("Test {0}", "this");
        }
    }
}

Upvotes: 4

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

#define in C# is used only to defines symbols, which can be used in #if directives.

From MSDN:

The #define directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.

Symbols can be used to specify conditions for compilation. You can test for the symbol with either #if or #elif. You can also use the conditional attribute to perform conditional compilation.

You can define a symbol, but you cannot assign a value to a symbol. The #define directive must appear in the file before you use any instructions that aren't also preprocessor directives.

There is a snippet you can use:

type cw and press TAB + TAB

Upvotes: 2

Related Questions