Quantcast
Channel: Tips for code-golfing in C# - Code Golf Stack Exchange
Browsing latest articles
Browse All 60 View Live

Answer by btnlq for Tips for code-golfing in C#

The first and third sections of for can contain multiple comma-separated statement expressions, including assignments (but not declarations) and method...

View Article



Answer by btnlq for Tips for code-golfing in C#

Use Range instead of Substring:var s="abcdef";Console.Write(s.Substring(2,2)); // "cd"Console.Write(s[2..4]); // "cd"It doesn't work if type is not known at compile time:dynamic...

View Article

Answer by Jeff Brophy for Tips for code-golfing in C#

Infinite LoopsDefault infinite loop provided in code golf is usually a while loop:while(true){...}This can be reduced (-1, as stated earlier) using an inequality:while(1>0){...}But it can be better...

View Article

Answer by José Mancharo for Tips for code-golfing in C#

Use .NET 6 Top Level Statements, File-Scoped Namespaces, and target-typed new()Upgrade to .net 6 and you can use single file programs with no boilerplate. You can also use file-scoped namespaces like...

View Article

Answer by Zuabros for Tips for code-golfing in C#

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 bytesAnother hint is a small way to use a loop,...

View Article


Answer by the default. for Tips for code-golfing in C#

Group statements via tuplesLet'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...

View Article

Answer by Adám for Tips for code-golfing in C#

Use dynamic instead of types with longer names in function declarationsFor example, instead ofDateTime f(int y)=>…usedynamic f(int y)=>…

View Article

Answer by the default. for Tips for code-golfing in C#

Use the weird kind of the is operatora is var balways defines the variable b equal to a and returns true. It is unclear how have the humans who design C# come up with this (inline variable declarations...

View Article


Answer by the default. for Tips for code-golfing in C#

Use dynamic to group declarationsdynamic 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...

View Article


Answer by the default. for Tips for code-golfing in C#

Avoid single-statement foreach loopsIf the loop's statement returns a non-int (including void!) "value", it can be replaced with LINQ:foreach(var x in...

View Article

Answer by dana for Tips for code-golfing in C#

Tuple DeconstructionIt 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,...

View Article

Answer by Gymhgy for Tips for code-golfing in C#

Swapping two variablesNormally, 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!...

View Article

Image may be NSFW.
Clik here to view.

Answer by dana for Tips for code-golfing in C#

C# Interactive WindowAKA C# (Visual C# Interactive Compiler) on Try it OnlineThis is a REPL for the C# language that includes many advantages to code golfing over using the traditional C#...

View Article


Answer by Gymhgy for Tips for code-golfing in C#

Using Command-Line OptionsCommand-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...

View Article

Answer by aloisdg for Tips for code-golfing in C#

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

View Article


Answer by user82593 for Tips for code-golfing in C#

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

View Article

Answer by digEmAll for Tips for code-golfing in C#

The Compute instance method of System.Data.DataTable, allows to evaluate a simple string expression, e.g. :C# (Visual C# Compiler), 166 bytesnamespace System.Data{ class P { static void Main() {...

View Article


Answer by aloisdg for Tips for code-golfing in C#

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

View Article

Answer by Kamil Drakari for Tips for code-golfing in C#

Implicitly typed arraysIf 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#...

View Article

Answer by TheLethalCoder for Tips for code-golfing in C#

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

View Article

Answer by TheLethalCoder for Tips for code-golfing in C#

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 includeusing System;or fully qualify the type when you otherwise...

View Article


Answer by TheLethalCoder for Tips for code-golfing in C#

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()>0Length>0Count>0Any()

View Article


Answer by TheLethalCoder for Tips for code-golfing in C#

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 codevs:namespace...

View Article

Answer by TheLethalCoder for Tips for code-golfing in C#

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;

View Article

Answer by VisualMelon for Tips for code-golfing in C#

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

View Article


Answer by Erresen for Tips for code-golfing in C#

Declare empty/matching strings togetherIf you need to declare multiple empty/matching strings, you can save a few bytes with the following:string a="";string b="";string c=""; // 36 bytesvar a="";var...

View Article

Answer by aloisdg for Tips for code-golfing in C#

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

View Article

Answer by aloisdg for Tips for code-golfing in C#

Use Action like Func to set a function to a variable. Action returns nothing (void) so it is great for printing.For example:Action<string>w=Console.WriteLine;w("Hello World");This tips is...

View Article

Answer by aloisdg for Tips for code-golfing in C#

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

View Article



Answer by aloisdg for Tips for code-golfing in C#

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!example: Code golf to make...

View Article

Answer by aloisdg for Tips for code-golfing in C#

Use the one character non-short-circuiting variants of logical operators where possible:i>0||i<42i>0|i<42or i>0&&i<42i>0&i<42The difference between the two are one...

View Article

Answer by aloisdg for Tips for code-golfing in C#

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}"example: Code golf to make logos for...

View Article

Answer by aloisdg for Tips for code-golfing in C#

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

View Article


Answer by Yytsi for Tips for code-golfing in C#

Instead ofbool a = true;bool b = false;dovar a=0<1;var b=1<0;If you need multiple variables, use this (suggested by @VisualMelon)bool a=0<1,b=!a;

View Article

Answer by raggy for Tips for code-golfing in C#

LINQInstead 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 usenew int[y].Select((_,i)=>f(i))if you need string or...

View Article

Answer by user42643 for Tips for code-golfing in C#

String InterpolationA 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...

View Article


Answer by Hand-E-Food for Tips for code-golfing in C#

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

View Article


Answer by SLuck49 for Tips for code-golfing in C#

You can use float and double literals to save a few bytes.var x=2.0;var y=2d; // saves 1 byteWhen you need some int arithmetic to return a float or double you can use the literals to force the...

View Article

Answer by Thomas Weller for Tips for code-golfing in C#

ReSharper tipsIf you have used ReSharper to get to the initial working solution before golfing, note that it often generatesreadonly variablesstatic methods, if they do not use any fieldsIf you have...

View Article

Answer by ProgramFOX for Tips for code-golfing in C#

Use lambdas to define a function in C# 6In 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;}

View Article

Answer by mirabilos for Tips for code-golfing in C#

Convert line endings from CRLF to LF before counting bytes ☺

View Article


Answer by InvisiblePanda for Tips for code-golfing in C#

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

View Article

Answer by maf-soft for Tips for code-golfing in C#

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

View Article


Answer by EvilFonti for Tips for code-golfing in C#

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

View Article

Answer by Nathan Cooper for Tips for code-golfing in C#

Effective use of usingYou can replacefloat (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...

View Article


Answer by M_J_O_N_E_S for Tips for code-golfing in C#

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

View Article

Answer by Cristian Lupascu for Tips for code-golfing in C#

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

View Article

Answer by Nellius for Tips for code-golfing in C#

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;

View Article

Answer by Joey for Tips for code-golfing in C#

Use var for declaring and initializing (single) variables to save characters on the type:string x="abc";becomesvar x="abc";Isn't particulaly necessary for int, of course.

View Article


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

View Article

Browsing latest articles
Browse All 60 View Live




Latest Images