62
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – krowe Jul 2 '14 at 5:48
  • \$\begingroup\$ Forgive me for the picture of a calendar, it was all I could find on short notice. \$\endgroup\$ – undergroundmonorail Jul 8 '14 at 12:44

51 Answers 51

59
\$\begingroup\$

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

.ToString() <-- 11 chars
+""         <--  3 chars
\$\endgroup\$
  • 5
    \$\begingroup\$ This also works in JS. \$\endgroup\$ – Cyoce Apr 5 '16 at 18:25
  • 1
    \$\begingroup\$ This is usually actually 5 chars if you need to use the string afterwards for including the braces... (1+"").DoSomethingWith1String(); \$\endgroup\$ – TheLethalCoder May 18 '17 at 12:48
  • 1
    \$\begingroup\$ If you need the string you're usually storing it. Just about any other usage can natively infer the ToString()... \$\endgroup\$ – jcolebrand May 18 '17 at 14:38
  • 1
    \$\begingroup\$ 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). \$\endgroup\$ – VisualMelon Jul 11 '17 at 20:01
  • 1
    \$\begingroup\$ Alternative - string interpolation: $"{n}" \$\endgroup\$ – Andriy Tolstoy Jan 4 at 11:24
41
\$\begingroup\$

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;
\$\endgroup\$
  • 9
    \$\begingroup\$ 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. \$\endgroup\$ – Nick Larsen Jan 31 '11 at 14:43
  • \$\begingroup\$ You can also just do using System;class P.... \$\endgroup\$ – ldam Jun 5 '15 at 19:15
  • \$\begingroup\$ @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. \$\endgroup\$ – Joey Jun 5 '15 at 20:28
  • \$\begingroup\$ 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. \$\endgroup\$ – milk Sep 1 '16 at 1:51
  • \$\begingroup\$ @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. \$\endgroup\$ – Joey Sep 1 '16 at 5:44
30
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ Remember that var cannot have multiple declarators, for example var x="x",y="y"; is not possible. \$\endgroup\$ – Ian H. Nov 22 '17 at 8:57
28
\$\begingroup\$

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

\$\endgroup\$
  • 2
    \$\begingroup\$ FWITW this is called η-reduction \$\endgroup\$ – ThreeFx Sep 13 '16 at 11:30
  • \$\begingroup\$ It's also known as "point free" style \$\endgroup\$ – Jonathan Wilson Mar 2 '17 at 18:04
  • 5
    \$\begingroup\$ To the more pragmatic of us, it's simply shorter :-þ \$\endgroup\$ – Joey Mar 3 '17 at 8:06
23
\$\begingroup\$

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!
\$\endgroup\$
  • \$\begingroup\$ This does usually involve ternary as well ;) \$\endgroup\$ – jcolebrand Jan 31 '11 at 14:47
  • 1
    \$\begingroup\$ As a C# golfer, you're really competing against the language Unbelievably related \$\endgroup\$ – dorukayhan Jul 19 '16 at 15:07
  • 1
    \$\begingroup\$ Actually, that's not true. It compiles using static int Main() as well, which would be 28 characters. \$\endgroup\$ – Metoniem Feb 14 '17 at 14:14
  • 1
    \$\begingroup\$ @Metoniem That requires a return something. \$\endgroup\$ – user202729 Mar 27 '18 at 14:54
21
\$\begingroup\$

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;
\$\endgroup\$
  • \$\begingroup\$ 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; \$\endgroup\$ – VisualMelon Jan 13 '17 at 9:37
18
\$\begingroup\$

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;
\$\endgroup\$
  • 15
    \$\begingroup\$ 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) \$\endgroup\$ – jcolebrand Jan 31 '11 at 14:31
  • \$\begingroup\$ 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. \$\endgroup\$ – Nick Larsen Jan 31 '11 at 15:01
  • 11
    \$\begingroup\$ No need for parentheses in the second case - j=i<1?1:0; is enough. \$\endgroup\$ – Danko Durbić Apr 18 '11 at 13:28
  • 3
    \$\begingroup\$ The question asks for tips which are somewhat specific to C#. This is one included in the tips for all languages. \$\endgroup\$ – Peter Taylor Mar 17 '14 at 20:35
  • 4
    \$\begingroup\$ @PeterTaylor I answered this question over 3 years ago, well before the thread you linked was created \$\endgroup\$ – Nellius Mar 18 '14 at 15:31
15
\$\begingroup\$

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

\$\endgroup\$
14
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ I think you need to remove () from the first line. \$\endgroup\$ – mellamokb Apr 13 '12 at 12:51
  • \$\begingroup\$ @mellamokb that's right, thanks! fixed. \$\endgroup\$ – Cristian Lupascu Apr 13 '12 at 13:50
  • 1
    \$\begingroup\$ Can't you do auto r=Console.ReadLine;? \$\endgroup\$ – Claudiu Sep 25 '14 at 16:36
  • 2
    \$\begingroup\$ @claudiu no, unfortunally not ideone.com/jFsVPX \$\endgroup\$ – Cristian Lupascu Sep 25 '14 at 17:19
  • \$\begingroup\$ @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. \$\endgroup\$ – GreatAndPowerfulOz Aug 8 '17 at 17:15
14
\$\begingroup\$

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>>
\$\endgroup\$
  • 7
    \$\begingroup\$ That is truly horrifying... I love it! \$\endgroup\$ – Alex Reinking Jul 9 '16 at 18:19
  • \$\begingroup\$ holy crap this is genius, I actually just saved a character while looping an array \$\endgroup\$ – Gaspa79 Apr 9 '17 at 6:13
  • \$\begingroup\$ This is truly evil! \$\endgroup\$ – GreatAndPowerfulOz Aug 8 '17 at 17:17
13
\$\begingroup\$

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;}
\$\endgroup\$
  • 3
    \$\begingroup\$ C#6 gives a whole new range of ability to code-golf \$\endgroup\$ – jcolebrand Jan 11 '15 at 23:32
  • \$\begingroup\$ 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. \$\endgroup\$ – TehPers Aug 4 '17 at 16:38
  • 1
    \$\begingroup\$ That's not formally a lambda. It's an expression bodied member. \$\endgroup\$ – recursive Nov 22 '17 at 22:32
13
\$\begingroup\$

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))
\$\endgroup\$
  • \$\begingroup\$ I use this trick in my answer for the Shamir's Secret Sharing challenge. \$\endgroup\$ – aloisdg Jul 7 '16 at 20:01
  • \$\begingroup\$ 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! \$\endgroup\$ – Gaspa79 Apr 9 '17 at 23:34
  • \$\begingroup\$ Yes enumerables are lazy but that is true for all three examples not just the one with the string. \$\endgroup\$ – raggy Apr 10 '17 at 16:39
11
\$\begingroup\$

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

\$\endgroup\$
  • 2
    \$\begingroup\$ And also "D d" instead of "var d" \$\endgroup\$ – Zukki Jun 4 '15 at 19:48
  • \$\begingroup\$ @Zukki Obviously! What was I thinking? :) \$\endgroup\$ – Cristian Lupascu Jun 5 '15 at 6:24
  • \$\begingroup\$ Alternative: using D = System.Collections.Generic.Dictionary<int,string>; \$\endgroup\$ – Andriy Tolstoy Jan 4 at 10:58
10
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Even shorter: (x-y)*1d/x/y; \$\endgroup\$ – recursive 2 days ago
9
\$\begingroup\$

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()
\$\endgroup\$
  • 5
    \$\begingroup\$ And always make the class one letter only :-) \$\endgroup\$ – Joey Jan 29 '11 at 11:40
  • 2
    \$\begingroup\$ Oh, and another nice thing, implied here: Main does not need any arguments in contrast to Java, for example. \$\endgroup\$ – Joey Jan 29 '11 at 19:10
  • \$\begingroup\$ @Joey: and neither does it need to be public. \$\endgroup\$ – R. Martinho Fernandes Jan 31 '11 at 2:36
  • 1
    \$\begingroup\$ @martinho ~ did you read my answer? ;) no public on main \$\endgroup\$ – jcolebrand Jan 31 '11 at 13:53
  • \$\begingroup\$ @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. \$\endgroup\$ – jcolebrand Jan 31 '11 at 13:54
9
\$\begingroup\$

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);
\$\endgroup\$
  • 11
    \$\begingroup\$ I never write the parentheses for one-parameter lambdas, even on production code. \$\endgroup\$ – R. Martinho Fernandes Feb 2 '11 at 1:34
  • \$\begingroup\$ I always use the brackets because I like to split the lambda into multiple lines for readability. \$\endgroup\$ – Juliana Peña Feb 2 '11 at 21:02
  • 2
    \$\begingroup\$ SomeCall(DoSomething) is even better \$\endgroup\$ – GreatAndPowerfulOz Aug 8 '17 at 17:18
9
\$\begingroup\$

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);
}
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Joey Mar 3 '11 at 10:49
  • \$\begingroup\$ @Joey In those cases I tend to switch to while(++i<max) which is the same length but easier to read. \$\endgroup\$ – ICR Dec 7 '11 at 14:17
  • \$\begingroup\$ ICR: depends on whether you can put another (earlier) statement into the for header as well, which would then save a character again. \$\endgroup\$ – Joey Dec 7 '11 at 15:09
  • \$\begingroup\$ You can move both declarations back into the for clause for a1 byte savings. \$\endgroup\$ – recursive Jul 4 '16 at 3:39
  • \$\begingroup\$ I like changing for(;i<max;) to while(i<max). Same number of bytes, but for me it just looks cleaner. \$\endgroup\$ – Ayb4btu Nov 10 '17 at 22:52
8
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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

\$\endgroup\$
  • 3
    \$\begingroup\$ Also note that i+$" bottles of beer"; is shorter than $"{i} bottles of beer". \$\endgroup\$ – aloisdg Jul 8 '16 at 14:56
  • 1
    \$\begingroup\$ @aloisdg In that first case you should leave $ out, though. \$\endgroup\$ – Metoniem Feb 14 '17 at 14:21
  • \$\begingroup\$ @Metoniem Indeed! I let it because in my original case I had two {i} one in front and one in the middle ;) \$\endgroup\$ – aloisdg Feb 14 '17 at 14:37
  • \$\begingroup\$ @aloisdg Ahh, I see. Yeah, shame comments can't be edited :( \$\endgroup\$ – Metoniem Feb 14 '17 at 14:40
6
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ Not sure if it's anywhere else in the tips but for this example you can use currying too... s=>c=>... \$\endgroup\$ – TheLethalCoder Jan 9 '17 at 14:30
  • \$\begingroup\$ @TheLethalCoder Indeed we can! I will update the answer thank you! \$\endgroup\$ – aloisdg Jan 10 '17 at 8:43
  • \$\begingroup\$ Can you use eta-reduction in this case? Something like this: s=>s.Contains. \$\endgroup\$ – corvus_192 Jan 11 '17 at 10:20
  • \$\begingroup\$ 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) \$\endgroup\$ – VisualMelon Jan 13 '17 at 9:34
  • \$\begingroup\$ Discussion about unamed functions \$\endgroup\$ – aloisdg Nov 24 '17 at 12:34
5
\$\begingroup\$

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.

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

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ .NetFiddle support .Dump() ;) \$\endgroup\$ – aloisdg Jul 8 '16 at 15:04
4
\$\begingroup\$

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

Instead of

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)

\$\endgroup\$
4
\$\begingroup\$

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
}
\$\endgroup\$
4
\$\begingroup\$

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);
//Addition and subtraction
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.

\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – ASCII-only Feb 20 at 3:42
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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 inspired by @W0lf great example of use of Func with ReadLine.

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Can you do var a=b=c="" like in javascript? \$\endgroup\$ – corvus_192 Jan 11 '17 at 10:22
  • \$\begingroup\$ @corvus_192 nope - unfortunately not. \$\endgroup\$ – Erresen Jan 11 '17 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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