# Tips for code-golfing in C#

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 ;)

• BEST TIP => Use something beside .NET if you don't want to submit the longest answer for the challenge. .NET is designed to be very verbose and to let the IDE do the typing. Which is actually not as bad as it sounds for general programming as long as you have that IDE crutch but for code golf that strategy is certain fail. – krowe Jul 2 '14 at 5:48
• Forgive me for the picture of a calendar, it was all I could find on short notice. – undergroundmonorail Jul 8 '14 at 12:44

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

.ToString() <-- 11 chars
+""         <--  3 chars

• This also works in JS. – Cyoce Apr 5 '16 at 18:25
• This is usually actually 5 chars if you need to use the string afterwards for including the braces... (1+"").DoSomethingWith1String(); – TheLethalCoder May 18 '17 at 12:48
• If you need the string you're usually storing it. Just about any other usage can natively infer the ToString()... – jcolebrand May 18 '17 at 14:38
• Note that this actually calls the static String.Concat(object) with the argument, rather than the virtual calling object.ToString(). Concat explicitly converts null to the empty string (see the reference source). There is no 'native casting' going on, you can convert anything like this, it's just that the result might not be very useful in some cases! (but the null behaviour may well be). – VisualMelon Jul 11 '17 at 20:01
• Alternative - string interpolation: $"{n}" – Andriy Tolstoy Jan 4 '19 at 11:24 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;  • 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. – Nick Larsen Jan 31 '11 at 14:43 • You can also just do using System;class P.... – ldam Jun 5 '15 at 19:15 • @Logan: This wasn't about just using System; but also about having an alias for a class in the same namespace, which is shorter the way I've shown here. – Joey Jun 5 '15 at 20:28 • It's even shorter to do using static System.Math; in C#6 (add you can use any of those functions as if they were truly global--not in a class). The original suggestion may still be shorter than using static if you need to access multiple classes. – milk Sep 1 '16 at 1:51 • @milk: the additional static keyword often is longer than any savings from leaving out M. on the method calls, but yes, it's an option, but it comes at a hefty upfront cost that needs lots of calls to amortise. – Joey Sep 1 '16 at 5:44 Use var for declaring and initializing (single) variables to save characters on the type: string x="abc";  becomes var x="abc";  Isn't particulaly necessary for int, of course. • Remember that var cannot have multiple declarators, for example var x="x",y="y"; is not possible. – Ian H. Nov 22 '17 at 8:57 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.) • FWITW this is called η-reduction – ThreeFx Sep 13 '16 at 11:30 • It's also known as "point free" style – Jonathan Wilson Mar 2 '17 at 18:04 • To the more pragmatic of us, it's simply shorter :-þ – Joey Mar 3 '17 at 8:06 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! • This does usually involve ternary as well ;) – jcolebrand Jan 31 '11 at 14:47 • As a C# golfer, you're really competing against the language Unbelievably related – user8397947 Jul 19 '16 at 15:07 • Actually, that's not true. It compiles using static int Main() as well, which would be 28 characters. – Metoniem Feb 14 '17 at 14:14 • – user202729 Mar 27 '18 at 14:54 Instead of bool a = true; bool b = false;  do var a=0<1; var b=1<0;  If you need multiple variables, use this (suggested by @VisualMelon) bool a=0<1,b=!a;  • Note that if you need multiple variables of the same type it is usually cheaper to declare the type a comma separate the declarations bool a=0<1,b=!a; – VisualMelon Jan 13 '17 at 9:37 Favor 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;  • 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. – Nick Larsen Jan 31 '11 at 15:01 • No need for parentheses in the second case - j=i<1?1:0; is enough. – Danko Durbić Apr 18 '11 at 13:28 • The question asks for tips which are somewhat specific to C#. This is one included in the tips for all languages. – Peter Taylor Mar 17 '14 at 20:35 • @PeterTaylor I answered this question over 3 years ago, well before the thread you linked was created – Nellius Mar 18 '14 at 15:31 ## Effective use of using You can replace float (which is an alias for System.Single) with z using z=System.Single; Then replace z=System.Single; with z=Single; by placing the program in the namespace System. (As with Joey's answer) This can be applied for other value types (use what they are an alias for), structs and classes When reading each character of a command line argument, rather than looping up to the string's length: static void Main(string[]a){ for(int i=0;i<a[0].Length;)Console.Write(a[0][i++]); }  You can save a character by using a try/catch block to find the end: static void Main(string[]a){ try{for(int i=0;;)Console.Write(a[0][i++]);}catch{} }  This applies to any array within an array such as: • string[] • int[][] • IList<IList<T>> • That is truly horrifying... I love it! – Alex Reinking Jul 9 '16 at 18:19 • holy crap this is genius, I actually just saved a character while looping an array – Gaspa79 Apr 9 '17 at 6:13 • This is truly evil! – GreatAndPowerfulOz Aug 8 '17 at 17:17 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 • I think you need to remove () from the first line. – mellamokb Apr 13 '12 at 12:51 • @mellamokb that's right, thanks! fixed. – Cristian Lupascu Apr 13 '12 at 13:50 • Can't you do auto r=Console.ReadLine;? – Claudiu Sep 25 '14 at 16:36 • @claudiu no, unfortunally not ideone.com/jFsVPX – Cristian Lupascu Sep 25 '14 at 17:19 • @Claudiu, auto is a C++ verb. var is for C#. The reason this can't be done is because Console.ReadLine is overloaded so the function signature needs to be specified in order to tell the compiler which overload is wanted. – GreatAndPowerfulOz Aug 8 '17 at 17:15 # Use lambdas to define a function in C# 6 In C# 6, you can use a lambda to define a function: int s(int a,int b)=>a+b;  This is shorter than defining a function like this: int s(int a,int b){return a+b;}  • C#6 gives a whole new range of ability to code-golf – jcolebrand Jan 11 '15 at 23:32 • In C#7, this can be done inside another function to create local functions. I doubt this will help while golfing, but it's still just a neat trick to know. – TehPers Aug 4 '17 at 16:38 • That's not formally a lambda. It's an expression bodied member. – recursive Nov 22 '17 at 22:32 # LINQ Instead of using: Enumerable.Range(0,y).Select(i=>f(i))  to get an Enumerable with the result of function f for every int in [0,y] you can use new int[y].Select((_,i)=>f(i))  if you need string or anything that implements Enumerable in your program you can use them too var s="I need this anyway"; s.Select((_,i)=>f(i))  • I use this trick in my answer for the Shamir's Secret Sharing challenge. – aloisdg moving to codidact.com Jul 7 '16 at 20:01 • I don't think that the string part will execute if you don't iterate the ienumerable with optimization on. Just failed for me until I did .ToArray();. Other than that, amazing tip! – Gaspa79 Apr 9 '17 at 23:34 • Yes enumerables are lazy but that is true for all three examples not just the one with the string. – raggy Apr 10 '17 at 16:39 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 D 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 • And also "D d" instead of "var d" – Zukki Jun 4 '15 at 19:48 • @Zukki Obviously! What was I thinking? :) – Cristian Lupascu Jun 5 '15 at 6:24 • Alternative: using D = System.Collections.Generic.Dictionary<int,string>; – Andriy Tolstoy Jan 4 '19 at 10:58 You can use float and double literals to save a few bytes. var x=2.0; var y=2d; // saves 1 byte  When you need some int arithmetic to return a float or double you can use the literals to force the conversion. ((float)a+b)/2; // this is no good (a+b)/2.0; // better (a+b)/2f; // best  If you ever run into a situation where you have to to cast you can save a few bytes by using multiplication instead. ((double)x-y)/(x*y); (x*1d-y)/(x*y); // saves 5 bytes  • Even shorter: (x-y)*1d/x/y; – recursive May 21 '19 at 20:08 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()  • And always make the class one letter only :-) – Joey Jan 29 '11 at 11:40 • 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 • @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 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);  • 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 • SomeCall(DoSomething) is even better – GreatAndPowerfulOz Aug 8 '17 at 17:18 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); }  • 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 • You can move both declarations back into the for clause for a1 byte savings. – recursive Jul 4 '16 at 3:39 • I like changing for(;i<max;) to while(i<max). Same number of bytes, but for me it just looks cleaner. – Ayb4btu Nov 10 '17 at 22:52 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. In C#, we are not allowed to do if(n%2) to check if n is a even number. If we do, we get a cannot implicity convert int to bool. A naive handling would be to do: if(n%2==0)  A better way is to use: if(n%2<1)  I used this to gain one byte here. note that this only works for positive numbers, as -1%2==-1, it is considered even with this method. ## String Interpolation A really simple space-saving improvement is interpolation. Instead of: string.Format("The value is ({0})", (method >> 4) + 8)  just use $ to inline expressions:

$"The value is ({(method >> 4) + 8})"  This, together with the new expression bodies in C#6.0 should make any simple string-calculation challenge pretty golfable in C#. • Also note that i+$" bottles of beer"; is shorter than $"{i} bottles of beer". – aloisdg moving to codidact.com Jul 8 '16 at 14:56 • @aloisdg In that first case you should leave $ out, though. – Metoniem Feb 14 '17 at 14:21
• @Metoniem Indeed! I let it because in my original case I had two {i} one in front and one in the middle ;) – aloisdg moving to codidact.com Feb 14 '17 at 14:37
• @aloisdg Ahh, I see. Yeah, shame comments can't be edited :( – Metoniem Feb 14 '17 at 14:40

Use C# lambda. Since PPCG allows lambda for input/output we should use them.

A classic C# methods looks like this:

bool Has(string s, char c)
{
return s.Contains(c);
}


As a lambda, we will write

Func<string, char, bool> Has = (s, c) => s.Contains(c);


Anonymous lambda are allowed too:

(s, c) => s.Contains(c)


Remove all the noise and focus!

Update:

We can improve one step more with currying as @TheLethalCoder comment:

s => c => s.Contains(c);


Example of curring by @Felix Palmen: How compute WPA key?

It will be helpful when you have exactly 2 parameters, then a empty unused variable _ will be better. See meta post about this. I use this trick here. You will have to change a bit the function. Example: Try it online!

• Not sure if it's anywhere else in the tips but for this example you can use currying too... s=>c=>... – TheLethalCoder Jan 9 '17 at 14:30
• @TheLethalCoder Indeed we can! I will update the answer thank you! – aloisdg moving to codidact.com Jan 10 '17 at 8:43
• Can you use eta-reduction in this case? Something like this: s=>s.Contains. – corvus_192 Jan 11 '17 at 10:20
• Note that C# and Java answers of the 'untyped lambda' variety are falling out of favour, you might wish to join the discussion on this meta post. The suggested alternative is (string s,char c)=>s.Contains(c) – VisualMelon Jan 13 '17 at 9:34
• Discussion about unamed functions – aloisdg moving to codidact.com Nov 24 '17 at 12:34

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.

• ditto with variable names – Nellius Jan 31 '11 at 14:07
• How is this "at least somewhat specific to C#"? – Peter Taylor Feb 21 '14 at 17:49

The Compute instance method of System.Data.DataTable, allows to evaluate a simple string expression, e.g. :

# C# (Visual C# Compiler), 166 bytes

namespace System.Data
{
class P
{
static void Main()
{
Console.Write(new DataTable().Compute("30*2+50*5/4",""));
}
}
}


Try it online!

Not very "golfy" per se, but sometimes might be useful.

# Swapping two variables

Normally, to swap two variables, you have to declare a temporary variable to store the value. It would look like something along the lines of this:

var c=a;a=b;b=c;


That's 16 bytes! There are some other methods of swapping that are better.

//Using tuples
(a,b)=(b,a);
//Bitwise xoring
a=a^b^(b=a);
a=a+b-(b=a);
//Multiplication and division
a=a*b/(b=a);


The last three only work for numeric values, and as ASCII-only pointed out, the last two might result in an ArithmeticOverflow exception. All of the above are 12 bytes, a 4 byte saving compared to the first example.

• Only applies for numbers though, and even then anything other than tuples and xor risk running into integer limits of you're applying this to integers. Occasionally, other number types will run into limits too – ASCII-only Feb 20 '19 at 3:42

Using LinqPad will give you the possibility to remove all the program overhead as you can execute statements directly. (And it should be fully legal in codegolf... No one says you need an .exe)

Output is done using the .Dump() extension method.

(A particular case of knowing your operator precedence!)

Use % for tight-binding (somewhat) limited subtraction. This can save you a pair of parentheses around a subtraction, the result of which you want to multiply or divide by something; but be careful, it has serious limitations.

char b='5'; // b is some ASCII input
int a=(b-48)*c; // we want to find the numerical value of b, and multiply it by something ('0'==48)


Consider

char b='5'; // b is some ASCII input
int a=b%48*c; // only good for ASCII within 48 of '0' (positive only)!


Examples:

'5'%'0'*2 -> 10
'5'%'0'*-1 -> -5
'5'%'0'/2 -> 2


I've only just discovered this, and I feel like it will be valuable thing to remember whenever working with ASCII in the future. (I'm currently golfing somewhere where I'm using ASCII for compact numeric representations, but needs to multiply by 1 or -1 based on another condition, and this striped 2 bytes)

If you need to include multiple usings that all fall off of the same hierarchy it is often shorter to use the longest one as the namespace:

using System;
using System.Linq;
//Some code


vs:

namespace System.Linq
{
//Some code
}


# Avoid single-statement foreach loops

If the loop's statement returns a non-int (including void!) "value", it can be replaced with LINQ:

foreach(var x in a)Console.WriteLine(F(x));
a.Any(x=>Console.WriteLine(F(x))is int);


If the value happens to be an int, you can use a condition that will always be true or always be false (for example, >0 or <n), a different type and/or All instead of Any.

# Use dynamic to group declarations

dynamic is a forgotten feature that literally performs dynamic typing in C#! It has limitations (doesn't support extension methods, is bad at inferring that you want to use it, ...), but can often save bytes by merging declarations of incompatible types. Compare the following:

var a=[something of type IEnumerable<int>];var b=[something of type string];int i=x+~y^z
dynamic a=[something of type IEnumerable<int>],b=[something of type string],i=x+~y^z


That's 4 bytes of savings!

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.