Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

What general tips do you have for golfing in C#? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C# (e.g. "remove comments" is not an answer). Please post one tip per answer.

-- borrowed from marcog's idea ;)

share|improve this question

14 Answers

Instead of using .ToString() use +"" for numerics and other types that can be natively cast to a string safely.

.ToString() <-- 11 chars
+""         <--  3 chars
share|improve this answer

Remember where private or public are inherent, such as the following:

class Default{static void Main()

as compared to

public class Default { public static void Main()
share|improve this answer
3  
And always make the class one letter only :-) – Joey Jan 29 '11 at 11:40
1  
Oh, and another nice thing, implied here: Main does not need any arguments in contrast to Java, for example. – Joey Jan 29 '11 at 19:10
@Joey: and neither does it need to be public. – R. Martinho Fernandes Jan 31 '11 at 2:36
1  
@martinho ~ did you read my answer? ;) no public on main – jcolebrand Jan 31 '11 at 13:53
@Joey ~ I was trying to keep it to one per post ;) ... figured someone else would post taht about main or classes only being one letter. Seeing as how nobody else has, I'll go ahead and add that one too. – jcolebrand Jan 31 '11 at 13:54
show 3 more comments

Use var for declaring and initializing variables to save characters on the type:

string x="abc";

gets

var x="abc";

Isn't particulaly necessary for int, of course.

share|improve this answer

I once deliberately placed my program in namespace System so I can shorten access to a specific class. Compare

using System;using M=System.Math;

to

namespace System{using M=Math;
share|improve this answer
6  
Just remember that it is better to fully qualify classes/functions when a single use solves the problem. This is only useful if you have to call something more than once, and even then only for items in the System namespace. – NickLarsen Jan 31 '11 at 14:43

Make classnames only one letter. Enhancing on Tips for code-golfing in C# we go from

class Default{static void Main()

to

class D{static void Main()

which knocks out another 6 chars in this case.

share|improve this answer
ditto with variable names – Nellius Jan 31 '11 at 14:07

Looping:

Variable declarations:

int max;
for(int i=1;i<max;i++){
}

become:

int max,i=1;
for(;i<max;i++){
}

And if you have a need to or work with the i variable only once, you could start at -1 (or 0 depending on the loop circumstance) and increment inline:

int max,i=1;
for(;i<max;i++){
  Console.WriteLine(i);
}

to

int max,i=1;
for(;i<max;){
  Console.WriteLine(++i);
}

And that reduces by one character, and slightly obfuscates the code as well. Only do that to the FIRST i reference, like thus: (granted one character optimizations aren't much, but they can help)

int max,i=1;
for(;i<max;i++){
  Console.WriteLine(i + " " + i);
}

to

int max,i=1;
for(;i<max;){
  Console.WriteLine(++i + " " + i);
}

when the loop does not have to increment i (reverse order loop):

for(int i=MAX;--i>0;){
      Console.WriteLine(i);
}
share|improve this answer
I usually put the ++ in such cases directly into the loop header: for(;++i<max;) which is both easier to follow and harder to get wrong. – Joey Mar 3 '11 at 10:49
@Joey In those cases I tend to switch to while(++i<max) which is the same length but easier to read. – ICR Dec 7 '11 at 14:17
ICR: depends on whether you can put another (earlier) statement into the for header as well, which would then save a character again. – Joey Dec 7 '11 at 15:09

Favour the ternary operator over if..else blocks where appropriate.

For example:

if(i<1)
    j=1;
else
    j=0;

is more efficiently:

j=(i<1)?1:0;
share|improve this answer
2  
Am I the only one that feels that the second case is inherently more readable for things like this in general? I do that routinely. In addition, if I need to avoid a null condition (like on a string) I do something like var x = input ?? ""; (I loves my coalesces) – jcolebrand Jan 31 '11 at 14:31
There are times when it is far from being the more readable option, particularly when i < 1 is a complex statement or when the name of j is long. IMO, it also fails to convey side effects very well. In the case where if (i < 1) is something like if (SendEmail(recipient)) which returns true/false depending on the success of the side effects, I prefer the if/then notation. – NickLarsen Jan 31 '11 at 15:01
@NickLarsen I meant only on simple assignments, I should have clarified. Yes, for things which may have side effects or which may call functions as the (1:0) spot, I don't prefer the short way, I agree with you and prefer the long way. But for defining defaults of the order int value; if (boolean == true) {value = 1;}else{value=2;} in that style I prefer the ternary. ~~ Anyways, I know this has been gone over time and time again on the intertubes ;) – jcolebrand Feb 1 '11 at 15:41
5  
No need for parentheses in the second case - j=i<1?1:0; is enough. – Danko Durbić Apr 18 '11 at 13:28

Remember that the smallest compilable program in C# is 29 characters:

class P
{
    static void Main()
    {   
    }
}

So start by removing that from your length and judge your answer on how much over that it takes. C# cannot compete with other languages when it comes to printing or reading input, which is the heart of most [code-golf] problems, so don't worry about that. As a C# golfer, you're really competing against the language.

A few other things to keep in mind:

  • Reduce all loops and if statements to a single line if possible in order to remove the brackets.
  • If given the option between stdin and command line, always use command line!
share|improve this answer
This does usually involve ternary as well ;) – jcolebrand Jan 31 '11 at 14:47

For one-line lambda expressions, you can skip the brackets and semicolon. For one-parameter expressions, you can skip the parentheses.

Instead of

SomeCall((x)=>{DoSomething();});

Use

SomeCall(x=>DoSomething);
share|improve this answer
2  
I never write the parentheses for one-parameter lambdas, even on production code. – R. Martinho Fernandes Feb 2 '11 at 1:34
I always use the brackets because I like to split the lambda into multiple lines for readability. – Juliana Peña Feb 2 '11 at 21:02

If using LINQ you can pass a method directly to Select instead of making a lambda.

So, instead of

foo.Select(x=>int.Parse(x))

you can use

foo.Select(int.Parse)

directly.

(Discovered recently when improving on one of Timwi's C# answers.)

share|improve this answer

If you need to use Console.ReadLine() multiple times in your code (min 3 times), you could do:

Func<string>r=Console.ReadLine;

and then just use

r()

instead

share|improve this answer
I think you need to remove () from the first line. – mellamokb Apr 13 '12 at 12:51
@mellamokb that's right, thanks! fixed. – w0lf Apr 13 '12 at 13:50

If you need to use a generic Dictionary<TKey, TValue> at least two times in your code, you could declare a dictionary class, like in this example:

class D:Dictionary<int,string>{}

and then just use

var d=new D{{1,"something"},{2,"something else"}};

instead of repeating Dictionary<int,string> for every instantiation.

I have used this technique in this answer

share|improve this answer

There are circumstances when an output parameter can save characters. Here's a slightly contrived example, a 10 pin bowling score algorithm.

With a return statement:

........10........20........30........40........50........60........70........80........90.......100.......110.......120.......130.......140.......150..
public double c(int[]b){int n,v,i=0,X=10;double t=0;while(i<19){n=b[i]+b[i+1];v=b[i+2];t+=(n<X)?n:X+v;if(b[i]>9)t+=b[i+(i>16|v!=X?3:4)];i+=2;}return t;}

And with an output parameter:

........10........20........30........40........50........60........70........80........90.......100.......110.......120.......130.......140.......
public void d(int[]b,out double t){int n,v,i=0,X=10;t=0;while(i<19){n=b[i]+b[i+1];v=b[i+2];t+=(n<X)?n:X+v;if(b[i]>9)t+=b[i+(i>16|v!=X?3:4)];i+=2;}}

The output parameter here saves a total of 5 characters.

share|improve this answer

Discovered tonight "in the trenches" while improving some golf code... if you have a class for your processing, you can do the work in the constructor to save declaring a method.

I discovered this while reducing a console application - as there was a static void Main(), all functions and variables had to be declared static. I created a nested class with member functions and variables, with the main work performed in the constructor. This also saves characters in the calling code.

e.g. Class with method:

class a
{
    public void b()
    {
        new c().d("input");
    }
}
class c
{
    public void d(string e)
    {
        System.Console.Write(e.Replace("in", "out"));
    }
}

Class with work in the constructor:

class a
{
    public void b()
    {
        new c("input");
    }
}
class c
{
    public c(string e)
    {
        System.Console.Write(e.Replace("in", "out"));
    }
}

This example saves 9 characters.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.