mohRamadan
mohRamadan

Reputation: 639

How to get value of escape characters in c#?

I want to know the ASCII value of an escape sequence in runtime. for example:

string x = "\\b";
char res = someFunctionCall(x);
//res = '\b' = 0x08

The difference here that I only know x at runtime.

I know that this can be made with simple switch (already doing that), but I was wondering if it can be made using some existing c# call. I tried Char.Parse(x), but it didn't work.


Edit: I'm not talking here about converting '\b' to its corresponding ASCII value, rather, I'd like to parse "\\b" as what you write in c# to get '\b'.

Upvotes: 0

Views: 296

Answers (1)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19179

There is slow but rather easy way to do this. compile your code at runtime and let c# compiler take care of that! I know its overkill for what you want. but it works.

Anyway as @JonSkeet noted you can use a dictionary for simple escape sequences. take your list from here https://msdn.microsoft.com/en-us/library/h21280bw.aspx

Here is solution by compiling code at runtime, Note that its VERY SLOW, so I suggest you to replace and map multiple characters at once so compiler only runs and evaluate all of that for you only once.

using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

//...

private static void Main()
{
    string x = "\\b";
    string res = Evaluate(x);
    Console.WriteLine(res);
}

public static string Evaluate(string input)
{
    // code to compile.
    const string format = "namespace EscapeSequenceMapper {{public class Program{{public static string Main(){{ return \"{0}\";}}}}}}";

    // compile code.
    var cr = new CSharpCodeProvider().CompileAssemblyFromSource(
        new CompilerParameters { GenerateInMemory = true }, string.Format(format, input));

    if (cr.Errors.HasErrors) return null;

    // get main method and invoke.
    var method = cr.CompiledAssembly.GetType("EscapeSequenceMapper.Program").GetMethod("Main");
    return (string)method.Invoke(null, null);
}

Upvotes: 1

Related Questions