Typesetting “C#” in LaTeX

How do you refer to the C# programming language in LaTeX? Simply typing C# doesn’t work because # is a special character in LaTeX. You could type C#. That works, but it looks a little odd. The number sign is too big and too low.

What about using a musical sharp sign, i.e. C$\sharp$? That also looks a little odd. Even though the language is pronounced “C sharp,” it’s usually written with a number sign, not a sharp.

Let’s look at recommended ways of typesetting C++ to see whether that helps. The top answer to this question on TeX Stack Exchange is to define a new command as follows:

\newcommand{\CC}{C\nolinebreak\hspace{-.05em}\raisebox{.4ex}{\tiny\bf +}\nolinebreak\hspace{-.10em}\raisebox{.4ex}{\tiny\bf +}}

This does several things. First, it prevents line breaks between the constituent characters. It also does several things to the plus signs:

  • Draws them in closer
  • Makes them smaller
  • Raises them
  • Makes them bold

The result is what we’re subconsciously accustomed to seeing in print.

Here’s an analogous command for C#.

\newcommand{\CS}{C\nolinebreak\hspace{-.05em}\raisebox{.6ex}{\tiny\bf \#}}

And here’s the output. The number sign is a little too small.

To make a little larger number sign, replace \tiny with \scriptsize.

More LaTeX posts

7 thoughts on “Typesetting “C#” in LaTeX

  1. The C# symbol you last give is too high… essentially, the positioning you want, to match most renderings of C# I’ve seen, is to make the top and bottom stroke of the octothorpe line up with the edges of the letter C’s terminals; the top stroke with the top terminal, and the bottom stroke with the bottom terminal. This may prove difficult with LaTeX as the octothorpe in the typeface shown (or how the ‘special char’ is drawn in stead of rendered fromt he font) has the spacing between the top and bottom strokes much narrower than most typefaces.

    This might be more correctable by using XeTeX for yout LaTeX processor with truetype fonts, set with setmainfont{Arial} (or some other better typeface).

  2. If you use the relsize package this lines up the octothorpe nicely:

    newcommand{CS}{Cnolinebreak[4]hspace{-.05em}raisebox{.4ex}{relsize{-2}{textbf{#}}}}

    Relsize is more robust anyway. tiny and scriptsize are not going to work well if you put the macro in a section title.

  3. yoursunny: Thanks. I lost the backslashes on my site years ago when restoring from a backup. Still find a missing backslash once in a while.

Comments are closed.