C # macro definitions in preprocessor

Can C # define macros, as is done in the C programming language, with instructions in front of the processor? I would like to simplify the regular typing of some duplicate statements, such as:

Console.WriteLine("foo"); 
+52
macros c # c-preprocessor
Apr 2 '09 at 12:12
source share
9 answers

No, C # does not support preprocessor macros such as C. Visual Studio, on the other hand, has fragments . Visual Studio snippets are an IDE feature and are extended in the editor, not replaced in the code when compiled by the preprocessor.

+40
Apr 02 '09 at 12:14
source share

You can use the C preprocessor (e.g. mcpp) and install it in a .csproj file. Then you execute the "build action" in the source file from "Compile to Preprocess" or whatever you call it. Just add BeforBuild to your .csproj as follows:

  <Target Name="BeforeBuild" Inputs="@(Preprocess)" Outputs="@(Preprocess->'%(Filename)_P.cs')"> <Exec Command="..\Bin\cpp.exe @(Preprocess) -P -o %(RelativeDir)%(Filename)_P.cs" /> <CreateItem Include="@(Preprocess->'%(RelativeDir)%(Filename)_P.cs')"> <Output TaskParameter="Include" ItemName="Compile" /> </CreateItem> 

You may need to manually compile Compile to Preprocess in at least one file (in a text editor) - then the "Preprocess" option should be available for selection in Visual Studio.

I know that macros are greatly abused and abused, but removing them is completely equally bad, if not worse. A classic macro usage example would be NotifyPropertyChanged . Every programmer who has had to rewrite this code manually thousands of times knows how painful it is without macros.

+29
Mar 29 '13 at 13:00
source share

I use this to avoid Console.WriteLine(...) :

 public static void Cout(this string str, params object[] args) { Console.WriteLine(str, args); } 

and then you can use the following:

 "line 1".Cout(); "This {0} is an {1}".Cout("sentence", "example"); 

it's concise and kindly scared.

+26
Sep 07 '12 at 15:47
source share

While you cannot write macros when it comes to simplifying things like your example, C # 6.0 now offers static applications. Here Martin Pernik's example gave his middle article :

 using static System.Console; // Note the static keyword namespace CoolCSharp6Features { public class Program { public static int Main(string[] args) { WriteLine("Hellow World without Console class name prefix!"); return 0; } } } 
+8
Nov 08 '15 at 3:13
source share

The direct equivalent of C-style macros in C #, but inline d static methods - with or without #if / #elseif / #else pragmas - is the closest you can get:

  /// <summary> /// Prints a message when in debug mode /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void Log(object message) { #if DEBUG Console.WriteLine(message); #endif } /// <summary> /// Prints a formatted message when in debug mode /// </summary> /// <param name="format">A composite format string</param> /// <param name="args">An array of objects to write using format</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void Log(string format, params object[] args) { #if DEBUG Console.WriteLine(format, args); #endif } /// <summary> /// Computes the square of a number /// </summary> /// <param name="x">The value</param> /// <returns>x * x</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Square(double x) { return x * x; } /// <summary> /// Wipes a region of memory /// </summary> /// <param name="buffer">The buffer</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void ClearBuffer(ref byte[] buffer) { ClearBuffer(ref buffer, 0, buffer.Length); } /// <summary> /// Wipes a region of memory /// </summary> /// <param name="buffer">The buffer</param> /// <param name="offset">Start index</param> /// <param name="length">Number of bytes to clear</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void ClearBuffer(ref byte[] buffer, int offset, int length) { fixed(byte* ptrBuffer = &buffer[offset]) { for(int i = 0; i < length; ++i) { *(ptrBuffer + i) = 0; } } } 

This works fine as a macro, but has a slight flaw: methods marked as inline d will be copied to the reflection part of your assembly, like any other β€œnormal” method.

+4
May 13 '15 at 15:33
source share

Fortunately, C # does not have a C / C ++-style preprocessor - only conditional compilation and pragmas are supported (and maybe something else that I can’t remember). Unfortunately, C # does not have metaprogramming capabilities (this may to some extent be relevant to your question).

+2
Apr 02 '09 at 12:15
source share

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

+2
Apr 02 '09 at 12:17
source share

I would suggest you write an extension, something like below.

 public static class WriteToConsoleExtension { // Extension to all types public static void WriteToConsole(this object instance, string format, params object[] data) { Console.WriteLine(format, data); } } class Program { static void Main(string[] args) { Program p = new Program(); // Usage of extension p.WriteToConsole("Test {0}, {1}", DateTime.Now, 1); } } 

Hope this helps (and not too late :))

0
Feb 07 2018-11-11T00:
source share

Since C # 7.0 supports using static directives and local functions, for most cases you do not need preprocessor macros.

0
Aug 17 '18 at 11:33
source share



All Articles