[Question]
  [
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 ;)
  
[Answer]
Instead of using `.ToString()` use `+""` for numerics and other types that can be natively cast to a string safely.
```
.ToString() <-- 11 chars
+""         <--  3 chars
```
[Answer]
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;
```
[Answer]
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](https://codegolf.stackexchange.com/questions/1159/numbers-sums-products/1181#1181).)
[Answer]
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.
[Answer]
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!
[Answer]
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](https://codegolf.stackexchange.com/users/26981/visualmelon))
```
bool a=0<1,b=!a;
```
[Answer]
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>>`
[Answer]
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
[Answer]
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;
```
[Answer]
## Effective use of using
You can [replace](https://codegolf.stackexchange.com/questions/26962/linear-function-solver-from-two-points-x-y/26976#26976) `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
[Answer]
# 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))
```
[Answer]
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](https://codegolf.stackexchange.com/a/84369/15214).
note that this only works for positive numbers, as `-1%2==-1`, it is considered even with this method.
[Answer]
# 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;}
```
[Answer]
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);
}
```
[Answer]
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](https://codegolf.stackexchange.com/a/5509/3527)
[Answer]
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);
```
[Answer]
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
```
[Answer]
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()
```
[Answer]
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.
[Answer]
# 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`.
[Answer]
# 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!
[Answer]
# 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)
```
[Answer]
## 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#.
[Answer]
If you need to include multiple `using`s 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
}
```
[Answer]
The [`Compute`](https://docs.microsoft.com/en-us/dotnet/api/system.data.datatable.compute?view=netframework-4.7.1#System_Data_DataTable_Compute_System_String_System_String_) instance method of `System.Data.DataTable`, allows to evaluate a simple string expression, e.g. :
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 166 bytes
```
namespace System.Data
{
    class P
    {
        static void Main()
        {
            Console.Write(new DataTable().Compute("30*2+50*5/4",""));
        }
    }
}
```
[Try it online!](https://tio.run/##RYw/C8IwFMT3fIqQKakai9qpY10FQcH5Gd8QyJ/ii4pIP3tsLNTfcBx3xxlaGTI5B/BIPRjkpzcl9HoPCdiH8RHjgIgff35KCpQgWcOf0d74AWyQaq7@o0IXA0WH@nK3CWXAFy/fZ7g6lEp30fePMRfbutosmrpq1juxFEKpdn4Z2KRDzl8 "C# (Visual C# Compiler) – Try It Online")
Not very "golfy" per se, but sometimes might be useful.
[Answer]
# 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.
[Answer]
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](http://www.c-sharpcorner.com/uploadfile/rmcochran/functional-programming-in-C-Sharp-currying/) as @TheLethalCoder comment:
```
s => c => s.Contains(c);
```
Example of curring by @Felix Palmen: [How compute WPA key?](https://codegolf.stackexchange.com/a/145763/15214)
It will be helpful when you have exactly 2 parameters, then a empty unused variable `_` will be better. See [meta post about this](https://codegolf.meta.stackexchange.com/q/12681/15214). I use this trick [here](https://codegolf.stackexchange.com/a/153236/15214). You will have to change a bit the function. Example: [Try it online!](https://tio.run/##XY7BSgMxFEX3@YrHbJoQDbqUNKUyC6FYKszCpcTXqK/GxCavBSnz7WN0U3F5L/dyDtZLzCVMh0rpFYavyuHDir/J9DnGgEw5VXMXUiiE/xb3lPZWYPS1wsNJAFT2TAi3v6/55nnX/gsY2FPpfQ3gYHpyi9PRF2DXdfYlF4lvLaGbLWdWa5zfXFvWDlXfsDkG81iIQwMFWbk0tlllShJ1112wGd7pU14ppVHZcbLirHDMtIW1b1MFP2ZwtpDpEKOyrRzFOH0D "C# (.NET Core) – Try It Online")
[Answer]
# 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>)
[Answer]
Make classnames only one letter. Enhancing on [Tips for code-golfing in C#](https://codegolf.stackexchange.com/questions/173/tips-for-code-golfing-in-c/175#175) we go from 
```
class Default{static void Main()
```
to
```
class D{static void Main()
```
which knocks out another 6 chars in this case.
[Answer]
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.
]