Click here to Skip to main content
15,896,201 members
Articles / Programming Languages / C#

A Macro Preprocessor in C#

Rate me:
Please Sign up or sign in to vote.
4.48/5 (14 votes)
6 Apr 20053 min read 109.6K   1.3K   28  
This library supplies the same macro substitution facilities as the C/C++ preprocessor.
using System;
using System.IO;

class PreproTest {
    static void Test(string s) {
        Console.WriteLine(ms.Substitute(s));
    }    
  
    static string Input() {
        Console.Write(">> ");
        return Console.In.ReadLine();
    }
    
    class MyMacroSubstitutor : MacroSubstitutor {
        public override string CustomReplacement(string s) {
            switch(s) {
            case "DATE": return DateTime.Now.ToString();  
            case "USER": return Environment.GetEnvironmentVariable("USERNAME"); 
            }
            return "";
        }
    }    
    
    static MacroSubstitutor ms = new MyMacroSubstitutor();    

    static void Main(string[] args) {                
        string line;
        ms.AddMacro("DATE",MacroEntry.Custom,null);
        ms.AddMacro("USER",MacroEntry.Custom,null);
        while((line = Input()) != null) {
            line = ms.ProcessLine(line);
            if (line != "")
                Console.WriteLine(line);
        }
    }
    
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
South Africa South Africa
Steve is the author of 'C++ By Example'
(Que 2002) and developer of the UnderC interactive C++ interpreter.

Comments and Discussions