# 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

(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're already using Linq in your answer and need to check for a none empty collection use Any(). Compare it to the following:

Count()>0
Length>0
Count>0
Any()


# C# Interactive Window

AKA C# (Visual C# Interactive Compiler) on Try it Online

This is a REPL for the C# language that includes many advantages to code golfing over using the traditional C# compiler.

Currently, the shortest full program to print Hello, World! using the traditional C# compiler is 67 bytes:

class P{static void Main(){System.Console.Write("Hello, World!");}}


Using the C# Interactive Window, you can do the same thing in 22 bytes:

Write("Hello, World!")


As you can see, ceremonial class definitions are not required. Also, a whole bunch of references are included by default. The current list is as follows:

• /r:System
• /r:System.Core
• /r:Microsoft.CSharp
• /u:System
• /u:System.IO
• /u:System.Collections.Generic
• /u:System.Console
• /u:System.Diagnostics
• /u:System.Dynamic
• /u:System.Linq
• /u:System.Linq.Expressions
• /u:System.Text

The System.Linq namespace is particularly handy as it allows you to write functional style programming which often saves many bytes. Many of the older C# answers added 18 bytes or so for this advantage, simply to import the library using System.Linq;. There are other hacks where solutions created their class in the System namespace to more succinctly access the Console object. None of this is needed with the C# Interactive Window.

# 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.

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.

When to use a space and when you can remove it.

After []

• int[] f(char[] a){Console.Write('a');}
• int[]f(char[]a){Console.Write('a');}

Before $ • return$"{a}"
• return$"{a}" (Add yours in comment I will edit) When you want to join something to output a string without delimiter, you should use string.Concat(), instead of string.Join("",); • string.Join("",) • string.Concat() One byte free! Also Concat() has a lot more signatures than Join. Check them on MSDN: Concat and Join. # Declare empty/matching strings together If you need to declare multiple empty/matching strings, you can save a few bytes with the following: string a="";string b="";string c=""; // 36 bytes var a="";var b="";var c=""; // 27 bytes string a="",b="",c=""; // 22 bytes string a="",b=a,c=a; // 20 bytes  Unfortunately var a="",b=a,c=a; is illegal, as implicitly type variable cannot have multiple declarators • Can you do var a=b=c="" like in javascript? – corvus_192 Jan 11 '17 at 10:22 • @corvus_192 nope - unfortunately not. – Erresen Jan 11 '17 at 10:41 Always use the alias for a type if you need to type as they are usually shorter than the full names. It also means you don't need to include using System;  or fully qualify the type when you otherwise wouldn't need to. For a full list of the aliases visit this SO answer: object: System.Object string: System.String bool: System.Boolean byte: System.Byte sbyte: System.SByte short: System.Int16 ushort: System.UInt16 int: System.Int32 uint: System.UInt32 long: System.Int64 ulong: System.UInt64 float: System.Single double: System.Double decimal: System.Decimal char: System.Char  Note that you can also use the alias for calling static methods, consider: System.String.Concat();  vs string.Concat();  If you're already using Linq in your code and need to create a list use the following: var l=new int[0].ToList();  Compared to: var l=new System.Collections.Generic.List<int>();  You can even initialise the list with values like: var l=new int[0]{1,2,3,4}.ToList();  • You can remove the 0 in your declaration. – PmanAce Feb 20 '19 at 19:35 If you want to return multiple values from a function, use C# 7 style tuples instead of out parameters: (int,int)d(int a,int b)=>(a/b,a%b);  • Oh, didn't knew this was possible in C#. Thanks for sharing, +1 from me! One thing to golf in your code is by using currying input, though (a=>b=> instead of (a,b)=>). Here is your code in action, which might be useful to add as example-link to your tip. Oh, and welcome to PPCG! :) – Kevin Cruijssen Aug 31 '18 at 14:53 • @KevinCruijssen posted here :) – aloisdg Jan 11 '19 at 9:14 # Use Ranges and indices (C# 8) You can use the type Index, which can be used for indexing. You can create one from an int that counts from the beginning, or with a prefix ^ operator that counts from the end: Index i1 = 3; // number 3 from beginning Index i2 = ^4; // number 4 from end int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Console.WriteLine($"{a[i1]}, {a[i2]}"); // "3, 6"


You can also use a Range type, which consists of two Indexes, one for the start and one for the end, and can be written with a x..y range expression. You can then index with a Range in order to produce a slice:

var slice = a[i1..i2]; // { 3, 4, 5 }


source

If you need to use an enum for a method it is often shorter to cast an int to it rather than using the value directly:

DayOfWeek.Sunday
(DayOfWeek)0;


# Tuple Deconstruction

It is possible to deconstruct a Tuple into variables using the following syntax:

var myTuple = (1, "red", new DateTime(2000, 1, 1));
var (i, c, d) = myTuple;


In a code-golf scenario, you could use this to pass a tuple into a function:

t=>{var(i,c,d)=t;Print(i);Print(c);Print(d);}


Try it online!

A more practical use of this is to decompose a list of tuples and iterate over them using foreach.

var myTuples = new[] {
(1, "red", new DateTime(2000, 1, 1)),
(2, "blue", new DateTime(2000, 1, 1))
};
foreach (var (i, c, d) in myTuples) {
Print(i);
Print(c);
Print(d);
}


Or in a code-golf scenario:

t=>{foreach(var(i,c,d)in t){Print(i);Print(c);Print(d);}}


Try it online!

# Group statements via tuples

Let's assume the simplest case: you have two statements that return a value and would like to group them into one that returns the second value (perhaps the first one has useful side effects):

(s1,o:s2).o


This can be used along with inline variable declarations via is:

(s1 is var x,o:f(x,g(x))).o


It also works with the void -> value transformation via is int (although it doesn't always help):

(Print(x)is int,o:f(x)).o


You can use the ternary operator to shorten complex if..else constructs even if you need to work on multiple or different variables in different branches. You can sometimes save some chars by doing all or part of the work in the 3rd part of a for. ...and also other "optimizations", you can find in this example, I submitted here (it increments all numbers in a string given as char array or StringBuilder):

for (int b=3, c, i=a.Length; i-->0;
b=48>c|c>57
?7
:b>2
?c>56?a[i]='0':++a[i]*0
:b
) c=a[i];


In two of the branches, b isn't really set; in two branches, a[i] is set even though it says b= in the beginning; in one case a[i] and b are set simultaneously...

c>56 is shorter than c==57

i=a.Length; i-->0; is a lot shorter than i=a.Length-1; i>=0; i--

One thing I just learned (which I didn't know but probably all of you do): You do not need a namespace at all. If it is a simple program which doesn't use many namespaces that you would need to shorten, just omit the namespace and start with class Foo{....

Any objections to this or hints why I shouldn't do this are very welcome, as I'm just writing up my first "golfed" (as far as I got) answer in C# ;-)

• Alternately by putting the namespace as system you can omit the common using System; declaration ... – jcolebrand Oct 29 '14 at 16:30

Convert line endings from CRLF to LF before counting bytes ☺

• This really applies to all languages, and preprocessor directives are pretty rare in C# golf, so few programs will ever need to be on more than one line. – VisualMelon Jan 3 '15 at 15:42
• Mh but it's still non-obvious to some people. And most other languages are more often seen on LF-only environments. I don't expect it to help much, but… why not? – mirabilos Jan 3 '15 at 15:43
• Most of the time, just remove newlines... – aloisdg Jul 8 '16 at 15:04

## ReSharper tips

If you have used ReSharper to get to the initial working solution before golfing, note that it often generates

• readonly variables
• static methods, if they do not use any fields

If you have R#, you want to use the inline method refactoring for methods that are only called once, since they only need the additional method declaration.

• Or Rider, which is currently in free beta (unlike R#). – mınxomaτ Jul 8 '16 at 15:41

# Implicitly typed arrays

If you need an array (or IEnumerable) initialized with constant data, the most naive implementation might be like so:

new int[6]{23,16,278,0,2,44}


It's well known that arrays in C# can have implicit length:

new int[]{23,16,278,0,2,44}


However, for certain data types C# will also be able to determine the base type for the array from its values, making the same declaration even shorter:

new[]{23,16,278,0,2,44}


Here is an example demonstrating that all these options create the same array.

Additionally, specifically if you are creating an array for inline declaration, the new[] can be removed as long as the declared variable is not implicitly typed, which can save some bytes:

var a=new[]{"woah"};
string[]b={"woah"};

• That last line is worth all the weight. Excellent tips! – jcolebrand Nov 15 '17 at 18:58

# Convert a string to an IEnumerable<char>

Common way would be to use .ToCharArray() (14 bytes) or even better .ToList() (11 bytes), but the best I found is to rely on .Skip(0) (8 bytes).

Most of the time you wont need anything and the string will be cast directly, but sometimes it matters:

string.Join("a","bb") // bb


vs

string.Join("a","bb".Skip(0)) // bab

• wait ToSkip is a thing? – ASCII-only Apr 27 '18 at 7:50
• @ASCII-only Skip ;) – aloisdg Apr 27 '18 at 11:03
• Then it's no longer 10 bytes – ASCII-only Apr 27 '18 at 11:05
• @ASCII-only yup. 8 bytes \o/ – aloisdg Apr 27 '18 at 11:07

# Using Command-Line Options

Command-line options are not included in the byte count of your program, so they are very useful. However, keep in mind that when you use a command-line option, you are not competing in C# anymore, you are competing in C# with -yourflag.

The syntax for them is to put a - or a / preceding the letter, and if there are any arguments, you use : to separate the option name from the argument.

There are 3 command-line options that I know of as of right now:

• /u or -u or /using or -using

• Acts as a using statement. Example: /u:System.Text.RegularExpressions. You can do static imports with them by just adding the class name, like /u:System.Text.RegularExpressions.Regex. For example, if you have /u:System.String as an option, you can just use Concat(yourString) instead of string.Concat(yourString). Sadly, aliasing doesn't seem to work. You can also put multiple imports on the same line with ; as a delimiter like this: /u:System.Math;System.CodeDom.
• /i or -i, activates REPL mode. Code from the input box is also evaluated and printed.

• Can be useful for situations where hard-coding is allowed, e.g. if input insertRandomTermHere output 3, if input anotherRandomTerm output 4, we can just do int insertRandomTermHere=3,anotherRandomTerm=4;. Try it online!
• /r or -r

• Acts as an assembly reference. Allows you to use types like those in System.Numerics or System.Drawing. If you want to use BigInteger, an assembly reference is required.

Meanwhile, happy ing!

• Where did you find these flags in the docs? I can only find something about the default Roslyn flags. – Kevin Cruijssen Jan 30 '19 at 10:55
• @KevinCruijssen Experimentation :) – Gymhgy Jan 30 '19 at 16:19
• github.com/dotnet/roslyn/pull/5857 – dana Jan 30 '19 at 20:31
• "Command-line options are not included in the byte count of your program" [citation needed] – Peter Taylor Apr 17 '19 at 7:04
• @PeterTaylor Added relevant link to meta – Gymhgy Apr 18 '19 at 2:25

# Use dynamic instead of types with longer names in function declarations

DateTime f(int y)=>
use
dynamic f(int y)=>

• Why wouldn't I just use var here? – jcolebrand Jan 8 '20 at 17:38
• @jcolebrand Clarified. – Adám Jan 8 '20 at 17:40

Remember that C# uses unicode (which includes ascii). All char are int under the hood.

For example 'a' is 97.

• n=>char.IsDigit(n)|char.IsUpper(n)
• n=>n>47&n<58|n>64&n<91 // note that I use a bitwise comparator see

Since char are int, you can increment them:

• for(int x=31;x<126;)Console.Write((char)++x);
• for(char x=' ';x<127;)Console.Write(x++);

Use the unicode table for reference. Be careful one byte != one character.

• ints are 4 bytes, but chars are only 2. – recursive May 21 '19 at 20:06

Here are my 5 cents:

You can plain replace Math.Max and Math.Min, the following way, to gain 6 bytes:

Math.Max(a,b); // turns into:
a>b?a:b;       // saving 6 bytes


Another hint is a small way to use a loop, when you are given a variable with "n" times that won't be used anymore (as it will flatten your variable);

for (int i=0;i<n;i++) // turns into:
while (n-->0)         // saving 8 bytes


Method string.Split(' ') has default value whitespace, so if input string has the usual ' ' separation, instead of:

string.Split(' ');


Write:

string.Split() // gain 3 bytes

• Some of these become easier with newer .net versions. I should've probably known ahead of time to lock it in at a specific version. These are good optimizations. – jcolebrand Aug 24 '20 at 19:32
• Not locking it allows the answers to improve and keep alive and updated. – Zuabros Aug 24 '20 at 20:17
• For nitpicking: “has default value space” actually should be “has default value whitespace”. So without ' ' the string will be split also on tab, newline and a few more characters. (“If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.” — String.Split Method) – manatwork Sep 21 '20 at 0:59