g | x | w | all
Bytes Lang Time Link
nan250721T155501Zromfir
001Multiply by literal e.g. 1f250425T081845Zjuanferr
nanThe first and third sections of for can contain multiple commaseparated statement expressions230507T121942Zbtnlq
nan230306T152215Zbtnlq
nan221124T055737ZJeff Bro
nanUse .NET 6 Top Level Statements220614T202909ZJosé
nan170804T142511ZTheLetha
nan200822T175709ZZuabros
nan200426T034308Zthe defa
nan200108T142306ZAdá
nan191122T151747Zthe defa
nan191122T142020Zthe defa
nan190130T061754ZGymhgy
nan190417T065124Zthe defa
nan190220T201522Zdana
nan190220T023823ZGymhgy
nan190130T193607Zdana
008Use Ranges and indices C#190109T170133Zaloisdg
007If you want to return multiple values from a function180831T110805Zuser8259
nanThe Compute instance method of System.Data.DataTable180710T115519ZdigEmAll
nanConvert a string to an IEnumerable180115T125529Zaloisdg
nan160710T151201Zaloisdg
nanUse var for declaring and initializing single variables to save characters on the type110129T114108ZJoey
nan171115T185251ZKamil Dr
nan170804T135043ZTheLetha
nan170804T133906ZTheLetha
nan170518T124605ZTheLetha
nan170518T123803ZTheLetha
nan170508T181510ZVisualMe
nan160213T125623ZYytsi
nanUse the one character nonshortcircuiting variants of logical operators where possible160708T135856Zaloisdg
nanIn C#160703T202913Zaloisdg
nan161225T121501ZErresen
nanRemember that C# uses unicode which includes ascii. All char are int under the hood.160708T143805Zaloisdg
nan160708T152521Zaloisdg
nanYou can use float and double literals to save a few bytes.150820T123458ZSLuck49
nanWhen you want to join something to output a string without delimiter160708T141123Zaloisdg
nan160708T135228Zaloisdg
nan160203T160712Zraggy
nan110131T142738ZNellius
nan160127T181458Zuser4264
nanWhen reading each character of a command line argument151108T221513ZHand-E-F
nanIf you need to use a generic Dictionary120413T074438ZCristian
nan150305T202725ZThomas W
006Use lambdas to define a function in C#150107T185347ZProgramF
nan140512T163412ZNathan
nanConvert line endings from CRLF to LF before counting bytes ☺150102T214442Zmirabilo
nanOne 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 shorten141029T083909ZInvisibl
nan140925T163033Zmaf-soft
nan140708T102709ZEvilFont
nanDiscovered tonight "in the trenches" while improving some golf code... if you have a class for your processing120604T220156ZM_J_O_N_
010There are circumstances when an output parameter can save characters. Here's a slightly contrived example120603T195056ZM_J_O_N_
nanIf you need to use Console.ReadLine multiple times in your code min 3 times120413T073904ZCristian
nan110131T141531Zjcolebra
nan110416T005918ZJoey
nanFor oneline lambda expressions110201T005636ZJuliana
029Remember that the smallest compilable program in C# is110131T144654ZNick Lar
nan110131T135537Zjcolebra
nan110129T114419ZJoey
nanRemember where private or public are inherent110129T061301Zjcolebra
nan110129T061118Zjcolebra

use (static) global include in csproj files: eg

<ItemGroup>
  <Using Include="System.Console" Static="True"/>
</ItemGroup>

to change Console.Write to Write

and to skip using statements in the file

Multiply by literal (e.g. 1f, 1d, 1m...) instead of casting:

(decimal)a/b

vs

1m*a/b

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

for(i=0,k=1;i<n;Console.WriteLine(k),k*=3)i++;

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 s="abcdef";
Console.Write(s[2..4]); // runtime error
Console.Write($"{s}"[2..4]); // "cd"

Infinite Loops

Default 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 reduced (-4) using a parameterless for command:

for(;;){...}

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 so:

namespace whatever;

Also, when you instantiate an object, if it's type can be inferred by the compiler, you can use a target-typed new() constructor. e.g.,

class C {}
C c=new();

See (https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/top-level-statements)

See Also (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/file-scoped-namespaces)

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 []{1,2,3,4}.ToList();

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

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

Use dynamic instead of types with longer names in function declarations

For example, instead of
DateTime f(int y)=>
use
dynamic f(int y)=>

Use the weird kind of the is operator

a is var b always 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 that return true for some reason seem to be beyond Javascript to me), but it works. It can sometimes be used to shorten code (this is an oversimplified example; savings can often be smaller or zero):

a=>{var b=f(a);return g(b,b);}
a=>g(f(a)is var b?b:b,b)

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!

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:

Meanwhile, happy ing!

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.

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!

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.

C# Interactive Window

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

C# Interactive

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:

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.

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

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.

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

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!

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.

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"};

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

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

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
}

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;

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

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;

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

or

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.

example: Code golf to make logos for New Stack exchange sites

Learn more about them on MSDN.

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.

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

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

For example 'a' is 97.

example: Code golf to make logos for New Stack exchange sites


Since char are int, you can increment them:

example: Print the ASCII printable character set

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

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.

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

When you want to join something to output a string without delimiter, you should use string.Concat(), instead of string.Join("",);

One byte free!

example: Code golf to make logos for New Stack exchange sites

Also Concat() has a lot more signatures than Join. Check them on MSDN: Concat and Join.

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

After []


Before $

example: Code golf to make logos for New Stack exchange sites


(Add yours in comment I will edit)

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

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;

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

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:

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

ReSharper tips

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

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.

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

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

Convert line endings from CRLF to LF before counting bytes ☺

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

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

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.

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.

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.

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

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

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

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

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:

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.

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;

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

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

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