# 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

Use the one character non-short-circuiting variants of logical operators where possible:

• i>0||i<42
• i>0|i<42

or

• i>0&&i<42
• i>0&i<42

The difference between the two are one byte (yeah!) and the short-circuit principle. In our first example if i>0 is true, i<42 wont be checked. We dont need it. With the bitwise, both will be evaluated.

• Your statement about short circuiting is incorrect, logical or (||) does indeed short circuit if the left operand is true. msdn.microsoft.com/en-us/library/6373h346.aspx – Phaeze Jul 11 '16 at 21:56
• @Phaeze Indeed I wrote the wrong one. Thank you. – aloisdg Jul 11 '16 at 23:55
• Technically none of these are bitwise operators, they are just non-short-circuiting Boolean operators, because they are operating on Booleans. – VisualMelon Jan 13 '17 at 21:17
• @VisualMelon MSDN uses "logical or bitwise OR" for "x | y" and "logical OR" for "x || y". What should I use? – aloisdg Jan 14 '17 at 15:21
• These are 'logical' (Boolean being the logic system). Bitwise would be for integer types. I like to make the distinction clear because the a lot of C# golfing can end up being a mix of both, and operator precedence can be a real pain (though they are the same for each type) – VisualMelon Jan 14 '17 at 17:16

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 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 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 # 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!") And yes, I added my answer just for this post ;) 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 • /u:System.Threading.Tasks 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. 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.

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;

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

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

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

• 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

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 at 20:06

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