Possible Duplicate:
How do I format my code blocks?

How do I get the following to show up (on stackoverflow) with color syntax highlighting?

class Foo { internal Foo() { for (int i = 0; i < 42; ++i); } }

  • 4
    Anyone editing that code block proper will nullify the question and its answers – random Oct 2 '11 at 22:55

See https://stackoverflow.com/editing-help.

Basically, for code, indent four spaces -- you can do this by pasting code then highlighting and hitting Ctrl+K or the { } button above the editing box.

As far as syntax highlighting, see Changes to syntax highlighting and Interface options for specifying language prettify.

The correct language will often be inferred by the tags on the question, but you can manually specify it with an HTML comment:

<!-- language: c# -->

    public static bool IsAwesome { get { return true; } }


<!-- language: lang-js -->

    setTimeout(function () { alert("JavaScript"); }, 1000);

before the code block.

| improve this answer | |
  • Shouldn't that be language: lang-cs per this answer? – hammar Oct 2 '11 at 22:56
  • That is a quote straight out of the official editing help page. If it's wrong, that definitely needs to be corrected. There are four examples of syntax highlighting comments, and other three do use that format. I'll add the JS example. – agf Oct 2 '11 at 22:59
  • 2
    @hammar: Both work; you can either use the prettify language code (lang-cs) or the tag (c#), because lang-cs is the default syntax highlighting language for the c# tag. – balpha Oct 3 '11 at 17:41
  • The HTML language comment thing doesn't work. Not in this example, not in my posts. – aalaap Jul 20 '16 at 12:35
  • @aalaap Did you do it exactly as shown in stackoverflow.com/editing-help#syntax-highlighting ? Is the post on Stack Overflow or another site? They may not be exactly the same. – agf Jul 20 '16 at 19:12
  • @agf It's right here on StackOverflow. I tried JS, C# and PHP, but all I can see is the <!-- language: xxx --> comment as a part of the grey, monospaced code block. That's what I see right up here in this answer too. – aalaap Jul 21 '16 at 8:36
  • I have found that ```php also works. – Theodore R. Smith Dec 23 '19 at 17:46

If you want to insert code inline like this int i = 0; use backticks: `int i = 0;`. If you want an entire block of code you can highlight it and then click the code button which looks like {}. You can also hit Ctrl+K while it's highlight, or just manually indent it all 4 spaces:

class Foo { internal Foo() { for (int i = 0; i < 42; ++i); } }
| improve this answer | |
  • I don't see anything about syntax highlighting, which is what he asked about? – agf Oct 3 '11 at 0:28
  • 2
    @agf That's because this is Meta not SO. Meta isn't for posting code, so it has no syntax highlighting. This exact post on SO will have syntax highlighting. – Paul Oct 3 '11 at 0:34

Not the answer you're looking for? Browse other questions tagged .