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

Forgive me for the picture of a calendar, it was all I could find on short notice.

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

This also works in JS.

@Cyoce And Java

This is usually actually 5 chars if you need to use the string afterwards for including the braces... (1+"").DoSomethingWith1String();

If you need the string you're usually storing it. Just about any other usage can natively infer the ToString()...

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

Alternative - string interpolation: $"{n}"

Yah, that just recently got added tho, compared to the 2011 post date.

@jcolebrand how about something like .ToString("dddd, dd MMMM yyyy HH:mm:ss")!???

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;

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.

You can also just do using System;class P....

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

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.

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

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

FWITW this is called η-reduction

It's also known as "point free" style

To the more pragmatic of us, it's simply shorter :-þ

Interesting! Would love to learn more. I asked a question over at softwareengineering @ThreeFx

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.

Remember that var cannot have multiple declarators, for example var x="x",y="y"; is not possible.

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!

This does usually involve ternary as well ;)

As a C# golfer, you're really competing against the language Unbelievably related

Actually, that's not true. It compiles using static int Main() as well, which would be 28 characters.

@Metoniem That requires a return something.

Be advised that starting with C# 9 you can use top-level statements thus making the smallest compilable program exactly 0 bytes (https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements)

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;

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;

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

That is truly horrifying... I love it!

holy crap this is genius, I actually just saved a character while looping an array

This is truly evil!

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

I think you need to remove () from the first line.

@mellamokb that's right, thanks! fixed.

Can't you do auto r=Console.ReadLine;?

@claudiu no, unfortunally not http://ideone.com/jFsVPX

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

You can do var r=Console.ReadLine; and var s=(int x)=>x*x; since C# 10

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;

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)

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.

@NickLarsen I meant only on simple assignments, I should have clarified. Yes, for things which may have side effects or which may call functions as the (1:0) spot, I don't prefer the short way, I agree with you and prefer the long way. But for defining defaults of the order int value; if (boolean == true) {value = 1;}else{value=2;} in that style I prefer the ternary. ~~ Anyways, I know this has been gone over time and time again on the intertubes ;)

No need for parentheses in the second case - j=i<1?1:0; is enough.

The question asks for tips which are somewhat specific to C#. This is one included in the tips for all languages.

@PeterTaylor I answered this question over 3 years ago, well before the thread you linked was created

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

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

I use this trick in my answer for the Shamir's Secret Sharing challenge.

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!

Yes enumerables are lazy but that is true for all three examples not just the one with the string.

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.

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

C#6 gives a whole new range of ability to code-golf

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.

That's not formally a lambda.  It's an expression bodied member.

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

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.

@Joey In those cases I tend to switch to while(++i<max) which is the same length but easier to read.

ICR: depends on whether you can put another (earlier) statement into the for header as well, which would then save a character again.

You can move both declarations back into the for clause for a1 byte savings.

I like changing for(;i<max;) to while(i<max). Same number of bytes, but for me it just looks cleaner.

Okay so change it?

If you won't need the variable again, you can use:  while(max-->0) { foo;}

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

And also "D d" instead of "var d"

@Zukki Obviously! What was I thinking? :)

Alternative: using D = System.Collections.Generic.Dictionary<int,string>;

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

I never write the parentheses for one-parameter lambdas, even on production code.

I always use the brackets because I like to split the lambda into multiple lines for readability.

SomeCall(DoSomething) is even better

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

Even shorter: (x-y)*1d/x/y;

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

And always make the class one letter only :-)

Oh, and another nice thing, implied here: Main does not need any arguments in contrast to Java, for example.

@Joey: and neither does it need to be public.

@martinho ~ did you read my answer? ;) no public on main

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

@drachenstern: I was constrasting it with Java, where you are forced to bow to the full signature: public static void main(String[] a).

Ohhh good point @Martinho

The example is wrong. Classes are internal by default, not public. Members are private by default, not public.

@KendallFrey, I think the point was that Main is a special case or doesn't need to be public?

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.

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.

is GC saves 1 byte

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!

One of the best tips on the page.

With C# 7, you can sometimes save another byte with tuples: var(a,i)=([...],[...]).

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)

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

Also note that i+$" bottles of beer"; is shorter than $"{i} bottles of beer".

@aloisdg In that first case you should leave $ out, though.

@Metoniem Indeed! I let it because in my original case I had two {i} one in front and one in the middle ;)

@aloisdg Ahh, I see. Yeah, shame comments can't be edited :(

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
}

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.

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.

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

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!

Not sure if it's anywhere else in the tips but for this example you can use currying too... s=>c=>...

@TheLethalCoder Indeed we can! I will update the answer thank you!

Can you use eta-reduction in this case? Something like this: s=>s.Contains.

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)

Discussion about unamed functions

With the release of C#9, you will be able to use top-level statements to save even more bytes if your code does not accept any input.

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)

Welcome to Code Golf, and nice tip!

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.

ditto with variable names

How is this "at least somewhat specific to 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 is done using the .Dump() extension method.

.NetFiddle support .Dump() ;)

Could you explain it a bit more?

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.
example: Code golf to make logos for New Stack exchange sites
Learn more about them on MSDN.

Your statement about short circuiting is incorrect, logical or (||) does indeed short circuit if the left operand is true. https://msdn.microsoft.com/en-us/library/6373h346.aspx

@Phaeze Indeed I wrote the wrong one. Thank you.

Technically none of these are bitwise operators, they are just non-short-circuiting Boolean operators, because they are operating on Booleans.

@VisualMelon MSDN uses "logical or bitwise OR" for "x | y" and "logical OR" for "x || y". What should I use?

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 I am not sure about what to write. Can you made a edit on my answer? Thank you for the comments!

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.

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

Can you do var a=b=c="" like in javascript?

@corvus_192 nope - unfortunately not.

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

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

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.

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

(s1 is var x,o:f(x,g(x))).o can usually be shortened to (s1 is{}x,o:f(x,g(x))).o now.

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.

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 New Stack exchange sites

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

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;

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

You can remove the 0 in your declaration.

new int[0]{1,2,3,4} is a syntax error. perhaps new[]{1,2,3,4} instead ?

@CaiusJard Probably a typo, removed it.

 int can be removed too for some more golfy goodness if it can infer the type from the init'r

@CaiusJard Good point, I think I've even done that a few times as well

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

@KevinCruijssen posted here :)

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

Some of these become easier with newer .net versions. I should've probably known ahead of time to lock it in at a specific version. These are good optimizations.

Not locking it allows the answers to improve and keep alive and updated.

For nitpicking: “has default value space” actually should be “has default value whitespace”. So without ' ' the string will be split also on tab, newline and a few more characters. (“If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.” —    String.Split Method)

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(;;){...}

Hey there, welcome to the code golf stack exchange! Great first answer!

This seems identical to the C answer

There's also l:...goto l; Which is same length as a parameterless for when you can't remove the for's brackets

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!

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

Then it's no longer 10 bytes

@ASCII-only yup. 8 bytes \o/

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!

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"

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

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.

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?

Most of the time, just remove newlines...

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

readonly variables
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#).

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

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

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

example: Print the ASCII printable character set
Use the unicode table for reference. Be careful one byte != one character.

ints are 4 bytes, but chars are only 2.

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 code-golfing!

Where did you find these flags in the docs? I can only find something about the default Roslyn flags.

@KevinCruijssen Experimentation :)

https://github.com/dotnet/roslyn/pull/5857

"Command-line options are not included in the byte count of your program" [citation needed]

@PeterTaylor Added relevant link to meta

Use dynamic instead of types with longer names in function declarations
For example, instead of
DateTime f(int y)=>…
use
dynamic f(int y)=>…

Why wouldn't I just use var here?

@jcolebrand Clarified.

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


text:
Finding "sub-palindromes".
The shortest code that finds all unique "sub-palindromes" of a string, that is: any substring with length > 1 that is a palindrome.
eg.1
input: "12131331"
output: "33", "121", "131", "313", "1331"

eg.2
input: "3333"
output: "33", "333", "3333"

Can a string be it's own sub-palindrome? Since a string is it's own substring.

@JPvdMerwe: Yes, off course.

Actually more importantly: what must the output of 333 be? Naively you'd end up printing 33 twice

@JPvdMerwe: '333' -> '33', '333'. I'll edit the question accordingly. Thanks.

How is the output specified? Comma-delimited with quotes areound each sub-palindrome as you demonstrate here? One sub-p per line?

Related: How exactly is the input specified? A single line with the string in question delimited by quotes?

For input, just get a single string: stdin, command line, whatever. For output, we expect a simple list; no special formatting necessary.

J, 24 31 40
~.(#~(1<#*]-:|.)&>),<\\.

Sample use:
   ~.(#~(1<#*]-:|.)&>),<\\. '12131331'
┌───┬───┬───┬────┬──┐
│121│131│313│1331│33│
└───┴───┴───┴────┴──┘
   ~.(#~(1<#*]-:|.)&>),<\\. '3333'
┌──┬───┬────┐
│33│333│3333│
└──┴───┴────┘

Take that, GolfScript!

Admit it, you just put a dump from /dev/random here to fool us ;-)

@Joey try it for yourself ;p (TBH, I didn't believe it could work either at first)

I'm fairly sure it's actual code. I spent a weekend trying to wrap my head around J, but failed miserably. Still, I recognize code; I just don't understand what it does ;-)

Can't this be shortened to ~.(#~(1<#*]-:|.)&>),<\\. (24 characters)?

@ephemient It does indeed.  (Looks like I was stuck in the "answer must be a function" mindset, which does not apply here.)  Edited, thanks!

I don't think this is a valid function, it's not even a valid train. [:~.@(#~(1<#*]-:|.)&>)@,<\\. would be valid. See Definition of a Function in Concatenative Languages.

The problem statement doesn't explicitly ask for a function. Are you denying my submission is "code"?

Does this work for 1213133121?

How about }.{./.~,<&(#~1<#*|.-:])\\.?

Python 124
r=raw_input()
l=range(len(r))
print', '.join(set('"'+r[i:j+1]+'"'for i in l for j in l if i<j and r[i:j+1]==r[i:j+1][::-1]))

Haskell 98, 88 91 96
import List
main=interact$show.filter(\x->length x>1&&x==reverse x).nub.(tails=<<).inits

Python - 138 136
This code does not duplicate sub-palindromes.
r=raw_input()
i,l=0,len(r)
j=l
a=[]
while i<l-1:
 t=r[i:j];j-=1
 if t==t[::-1]:a+=['"'+t+'"']
 if j<i+2:i+=1;j=l
print", ".join(set(a))

Change '"'+t+'"' to t to save some space, although it uses single quotes.

Ruby - 126 102 97 characters
s=gets
*m=*0..s.size
puts m.product(m).map{|h,j|(c=s[h,j+1]).size>1&&c==c.reverse ? c:0}.uniq-[0]

Golfscript, 48 characters
subpalindrome.gs
{,}{(;}/{{,}{);}/}%{+}*{.,1>\.-1%=*},.&{`}%", "*

Usage:
echo "12131331" | ruby golfscript.rb subpalindrome.gs

The first operation {,}{(;}/ turns a string into a list of trailing-substrings. A similar leading-substrings transform is then mapped over the result. Then flatten with {+}*, filter for palindromes using the predicate .,1>\.-1%=*, grab unique values with .&, then pretty print.
It would be neater to extract the trailing-substrings transform as a block and reuse it as a replacement for leading-substrings after reversing each trailing substring, but I can't figure out a succinct way of doing that.

Vyxal, 7 bytes
ǎU~Ḣ'Ḃ=

Try it Online!
-1 thanks to lyxal
 U      # Unique
ǎ       # Substrings
  ~     # Where
   Ḣ    # Length > 1
    '   # And
     Ḃ= # Is palindromic

What an epic gamer, beating everyone. Very cool

@lyxal If I had  an accept for everything I've won...

@Ausername technically this doesn't actually work because it needs to output only the unique strings. So adding `;U` would do it. Apart from that the use of Ḣ was smart

Oh actually, you can use @shaggy's japt answer and uniquify before filtering

@Underslash Thanks! Will fix.

Try it Online! for 7 or 5.5 bytes depending on whether you Vyncode

Haskell - 170, 153
import Data.List
import Data.Set
p a=fromList$[show x|x<-subsequences a,x==reverse x,length x>1]
main=getLine>>=(\x->putStrLn$intercalate", "$toList$p x)

Replace main=getLine>>=(\x->putStrLn$intercalate", "$toList$p x) with main=getLine>>=putStrLn.intercalate", ".toList.p. I would also substitute a call to p with its body.

Substrings /= subsequences! Your program reports more subpalindromes than the reference output for example 1. ("1111" for instance)

Windows PowerShell, 104 109 111
0..($l=($s="$input").length-1)|%{($a=$_)..$l|%{-join$s[$a..$_]}}|sort -u|?{$_[1]-and$_-eq-join$_[$l..0]}

This expects the input on stdin and will throw all found palindromes one per line on stdout:
PS Home:\SVN\Joey\Public\SO\CG183> '12131331'| .\subp.ps1
33
121
131
313
1331

(When run from cmd it becomes echo 12131331|powershell -file subp.ps1 – it's just that $input takes a slightly different meaning depending on how the script was called, but it can be stdin, just not interactively.)
2011-01-30 13:57 (111) – First attempt.
2011-01-30 13:59 (109) – Inlined variable declaration.
2011-06-02 13:18 (104) – Redone substring finding by joining a char array instead of calling .Substring() and inlined a bit more.

J, 48
f=:,@:".
h=:\\.
~.(#~10&<)((]h-:"0&f|.h)#[:f]h)

eg
~.(#~10&<)((]h-:"0&f|.h)#[:f]h) '12131331'
121 131 313 1331 33

Prolog, 92
f(S,P):-append([_,X,_],S),X=[_,_|_],reverse(X,X),atom_codes(P,X).
p(S,R):-setof(P,f(S,P),R).

Sample use:
?- p("12131331",R).
R = ['121', '131', '1331', '313', '33'].

?- p("3333",R).
R = ['33', '333', '3333'].

Q, 78
{a::x;(?)(,/)b@'(&:')({x~(|:)x}'')b:-1_1_'({(sublist[;a]')x,'1+c}')c::(!)(#)a}

usage
q){a::x;(?)(,/)b@'(&:')({x~(|:)x}'')b:-1_1_'({(sublist[;a]')x,'1+c}')c::(!)(#)a}"12131331"
"121"
"131"
"313"
"1331"
"33"
q){a::x;(?)(,/)b@'(&:')({x~(|:)x}'')b:-1_1_'({(sublist[;a]')x,'1+c}')c::(!)(#)a}"3333"
"33"
"333"
"3333"

Retina, 34 27 bytes
&@!`(.)+.?(?<-1>\1)+(?(1)^)

Try it online!
The test suite needs an M because it is followed by another stage to insert empty lines between test cases.
Explanation
&@!`(.)+.?(?<-1>\1)+(?(1)^)

Print (!) all unique (@), overlapping (&) matches of the regex (.)+.?(?<-1>\1)+(?(1)^). This matches a palindrome of length 2 or more using balancing groups. There's a caveat to the "all overlapping matches" part: we can get at most one match per starting position. However, if two palindromes of different length begin at the same position, the shorter palindrome will appear again at the end of the longer palindrome. And since the greediness of + prioritises longer matches, we're getting all palindromes anyway.

05AB1E, 11 10 bytes
ŒÙʒÂQ}žQSK

Try it online!

9 bytes

@scottinet fails for singles, E.G.1234142141410010101000

Yours too, but not in the same way. o_O There is something going on that needs investigation. In the meantime, here is a 10 bytes version that seems to work

There was a bug with uniquify, I fixed it. Now both your 11 bytes answer and my 9 bytes one work :-)

@scottinet Your 10-byter can be a 9-byter as well by changing 1› to ≠. :)

Japt, 9 bytes
ã â fÅfêU

Try it
ã â fÅfêU     :Implicit input of string
ã             :Substrings
  â           :Deduplicate
    f         :Filter elements that return truthy
     Å        :  Slice off first character
       f      :Filter elements that return true
        êU    :  Test for palindrome

Factor, 70 bytes
[ all-subseqs [ length 1 > ] filter [ dup reverse = ] filter members ]

Try it online!
Having the two filters is actually shorter than having a single filter with some kind of and logic, or applying a single filter to two quotations with bi@.

all-subseqs Get all subsequences of the input.
[ length 1 > ] filter Take those with a length greater than one.
[ dup reverse = ] filter Take the palindromes.
members Remove duplicates.

Using locals ties the byte count:
[ all-subseqs [| s | s length 1 > s s reverse = and ] filter members ]

Scala 156 170
object o extends App{val l=args(0).length-2;val r=for(i<-0 to l;j<-i to l;c=args(0).substring(i,j+2);if(c==c.reverse))yield c;print(r.toSet.mkString(" "))}

object o{def main(s:Array[String]){val l=s(0).length-2;val r=for(i<-0 to l;j<-i to l;c=s(0).substring(i,j+2);if(c==c.reverse)) yield c;println(r.distinct.mkString(" "))}}

Hi Lalith, I shortened your code a bit: No blank before yield and extending App instead of overwriting main, println => print and distinct=>toSet

Scala 127
object p extends App{val s=args(0);print(2.to(s.size).flatMap(s.sliding(_).toSeq.filter(c=>c==c.reverse)).toSet.mkString(" "))}

To keep this an apples to apples comparison with the other Scala answer, I also made mine an object that extends App. Rather than iterate the input string manually and use substring, I leveraged sliding() to create a sequence of all the substrings for me.

Python, 83 102  chars
s=lambda t:(t[1:]or())and(t,)*(t==t[::-1])+s(t[1:])+s(t[:-1])
print set(s(input()))

The phrase (t[1:]or())and... is equivalent to (...)if t[1:]else() and saves one character!  I'm overly proud of this, given the savings.
Example:
python x
"51112232211161"
set(['11', '22', '11122322111', '161', '111', '112232211', '1223221', '22322', '232'])

Perl, 112
$_=<>;chop;s/./$&$' /g;
map{/../&&$_ eq reverse&&$h{$_}++}split/ /
  for grep{s/./$`$& /g}split/ /;
print for keys %h

Clojure, 81 bytes
#(set(for[i(range 2(+(count %)1))p(partition i 1 %):when(=(reverse p)(seq p))]p))

for was a perfect match here :) Could use :when(=(reverse p)p) if input was a list of characters OR a full string didn't count as a palindrome, actually in that case the max range of i could be (count %) as well.
Most compact case for reference:
#(set(for[i(range 2(count %))p(partition i 1 %):when(=(reverse p)p)]p))

JavaScript (ES6), 120 bytes
a=>{for(b=0,c=d=a.length,e=[];b<d;--c<b+2?(b++,c=d):1)(f=a.slice(b,c))==f.split``.reverse().join``&&e.push(f);return e}

This function takes a string as input and outputs an array.

Jelly, 9 bytes
ẆQŒḂÐfḊÐf

Try it online!

The output of your permalink is incorrect.

@Dennis why did this become a dupe target then >_> fixed

7 bytes with new Jelly.

Perl 6,  35  32 bytes
{unique ~«m:ex/(.+).?<{$0.flip}>/}

Test it
{set ~«m:ex/(.+).?<{$0.flip}>/}

Test it
Expanded:
{  # bare block lambda with implicit parameter ｢$_｣

  set             # turn into a Set object (ignores duplicates)

  ~«\             # stringify ｢~｣ all of these ｢«｣ (possibly in parrallel)
                  # otherwise it would be a sequence of Match objects

  m               # match
  :exhaustive     # in every way possible
  /
    ( .+ )        # at least one character ｢$0｣
    .?            # possibly another character (for odd sized sub-palindromes)
    <{ $0.flip }> # match the reverse of the first grouping
  /
}

Perl, 43 40 bytes
Includes +1 for n
perl -nE 's/(?=((.)((?1)|.?)\2)(?!.*\1))/say$1/eg' <<< 12131331

Coconut, 69 bytes
def f(s)=s and{s*(s[::-1]==s>""<s[1:])}-{""}|f(s[1:])|f(s[:-1])or s{}

Try it online!

Python 2, 73 bytes
f=lambda s:s and{s*(s[::-1]==s>""<s[1:])}-{""}|f(s[1:])|f(s[:-1])or set()

Try it online!

APL (Dyalog Classic), 27 bytes
{∪⍵/⍨≡∘⌽¨⍨⍵}∘⊃(,/1↓⍳∘≢,/¨⊂)

Try it online!
{∪⍵/⍨≡∘⌽¨⍨⍵}∘⊃(,/1↓⍳∘≢,/¨⊂)    Monadic train:
                           ⊂     Enclose the input, ⊂'12131331'
                     ⍳∘≢          Range from 1 to length of input
                     ⍳∘≢,/¨⊂      List of list of substrings of each length
                   1↓            Remove the first list (length-1 substrings)
               ⊃ ,/              Put the rest of the substrings into a single list.
{∪⍵/⍨≡∘⌽¨⍨⍵}                   To the result, apply this function which
                                   keeps all palindromes from a list:
      ≡∘⌽¨⍨⍵                    Boolean value of whether each (¨) string in argument
      ≡∘⌽ ⍨                     is equal to its own reverse

  ⍵/⍨                           Replicate (filter) argument by those values.
                                 This yields the length >1 palindromes.
∪                                Remove duplicates from the list of palindromes.

Due to OP calling for "code", the snippet ∪w/⍨≡∘⌽¨⍨w←⊃,/1↓(⍳∘≢,/¨⊂) is valid.

@Adám I think I'll keep this answer as it is for the sake of modern site standards, especially since it doesn't get the overall win.

APL(NARS), 65 chars, 130 bytes
{0=≢m←∪b/⍨{1≥≢⍵:0⋄∧/⍵=⌽⍵}¨b←↑∪/{x[⍵;]⊂y}¨⍳≢x←11 1‼k k⊢k←≢y←⍵:⍬⋄m}

test:
  r←{0=≢m←∪b/⍨{1≥≢⍵:0⋄∧/⍵=⌽⍵}¨b←↑∪/{x[⍵;]⊂y}¨⍳≢x←11 1‼k k⊢k←≢y←⍵:⍬⋄m}
  o←⎕fmt
  o r '1234442'
┌2───────────┐
│┌2──┐ ┌3───┐│
││ 44│ │ 444││
│└───┘ └────┘2
└∊───────────┘
  o r '3333'
┌3───────────────────┐
│┌4────┐ ┌3───┐ ┌2──┐│
││ 3333│ │ 333│ │ 33││
│└─────┘ └────┘ └───┘2
└∊───────────────────┘
  o r  "12131331"
┌5─────────────────────────────────┐
│┌4────┐ ┌3───┐ ┌2──┐ ┌3───┐ ┌3───┐│
││ 1331│ │ 121│ │ 33│ │ 313│ │ 131││
│└─────┘ └────┘ └───┘ └────┘ └────┘2
└∊─────────────────────────────────┘
  o r '1234'
┌0─┐
│ 0│
└~─┘

{0=≢m←∪b/⍨{1≥≢⍵:0⋄∧/⍵=⌽⍵}¨b←↑∪/{x[⍵;]⊂y}¨⍳≢x←11 1‼k k⊢k←≢y←⍵:⍬⋄m}
 y←⍵  assign the argument to y (because it has to be used inside other function)
 x←11 1‼k k⊢k←≢y   assign the lenght of y to k, call the function 11 1‼k k
                   that seems here find all partition of 1 2 ..k
 {x[⍵;]⊂y}¨⍳≢      make partition of arg ⍵ using that set x
 ∪/                set union with precedent to each element of partition y (i don't know if this is ok)
 b←↑               get first assign to b
 {1≥≢⍵:0⋄∧/⍵=⌽⍵}¨ for each element of b return 1 only if the argument ⍵ is such that
                   "∧/⍵=⌽⍵" ⍵ has all subset palindrome, else return 0
 b/⍨               get the elements in b for with {1≥≢⍵:0⋄∧/⍵=⌽⍵} return 1
 m←∪               make the set return without ripetition element, and assign to m
 0=≢               if lenght of m is 0 (void set) than
 :⍬⋄m              return ⍬ else return m

it someone know better why, and can explain this better, free of change this all... I am not so certain of this code, possible if test examples are more numerous, something will go wrong...

Japt, 14 bytes
Êò2@ãX fêSÃc â

Try it online!
Explanation:
Êò2               #Get the range [2...length(input)]
   @      Ã       #For each number in that range:
    ãX            # Get the substrings of the input with that length
       fêS        # Keep only the palindromes
           c      #Flatten
             â    #Keep unique results

PowerShell, 99 bytes
$args|% t*y|%{$s+=$_
0..$n|%{if($n-$_-and($t=-join$s[$_..$n])-eq-join$s[$n..$_]){$t}}
$n++}|sort -u

Try it online!
Less golfed:
$args|% toCharArray|%{
    $substring+=$_
    0..$n|%{
        if( $n-$_ -and ($temp=-join$substring[$_..$n]) -eq -join$substring[$n..$_] ){
            $temp
        }
    }
    $n++
}|sort -Unique

Brachylog, 11 bytes
{s.l>1∧.↔}ᵘ

Try it online!
(The header in the link is broken at the time of posting, so here's the predicate (function-equivalent in Brachylog) on only the first test case, with a w at the end to actually print the output.)
               The output is
{        }ᵘ    a list containing every possible unique
 s.            substring of
               the input
   l           the length of which
    >          is greater than
     1         one
      ∧        and
       .       which
        ↔      reversed
               is itself. (implicit output within the inline sub-predicate)

I feel like there's a shorter way to check that the length is greater than 1. (If it didn't filter out trivial palindromes, it would just be {s.↔}ᵘ.)

Stax, 10 bytes
îmmW┴√▄○○←

Run and debug it
I couldn't find an is-palindrome function. With that this'd probably be much shorter.

Husk, 11 9 8 bytes
Edit: -1 byte thanks to Razetime
uftfS=↔Q

Try it online!
uftfS=↔Q
u               # unique elements of
       Q        # all contiguous subsets of input
 f              # after filtering to include only those that
  t             # are not a single digit/character
   f            # and then filtering to include only those that
    S=↔         # are equal to themselves reversed

when in doubt, filter twice

8 bytes

Thanks!  I think I maybe need a look-up table to indicate when combinators actually save bytes, and when they're just a complicated liability...

§ generally isn't worth it in a full program(Or inside brackets). Removing them makes type inference happy,

Thunno 2, 7 bytes
FœḣæḲ:U

Try it online!
Explanation
FœḣæḲ:U  # Implicit input
F        # All substrings of the input
 œḣ      # Filter by length > 1
   æḲ:   # Only keep palindromes
      U  # Uniquify this list
         # Implicit output

Nekomata, 8 bytes
qNᵗz:↔=ũ

Attempt This Online!
qNᵗz:↔=ũ
q           Find a contiguous subsequence of the input
 N          Check that it is nonempty
  ᵗz        Check that it is not a singleton
    :       Duplicate
     ↔      Reverse
      =     Check equality
       ũ    Remove duplicate results

Java 8, 202 201 199 bytes
import java.util.*;s->{Set r=new HashSet();String x;for(int l=s.length(),i=0,j;i<l;i++)for(j=i;++j<=l;)if((x=s.substring(i,j)).contains(new StringBuffer(x).reverse())&x.length()>1)r.add(x);return r;}

Try it here.
If a function isn't allowed and a full program is required, it's 256 255 253 bytes instead:
import java.util.*;interface M{static void main(String[]a){Set r=new HashSet();String x;for(int l=a[0].length(),i=0,j;i<l;i++)for(j=i;++j<=l;)if((x=a[0].substring(i,j)).contains(new StringBuffer(x).reverse())&x.length()>1)r.add(x);System.out.print(r);}}

Try it here.
Explanation:
import java.util.*;      // Required import for Set and HashSet

s->{                     // Method with String parameter and Set return-type
  Set r=new HashSet();   //  Return-Set
  String t;              //  Temp-String
  for(int l=s.length(),  //  Length of the input-String
          i=0,j;         //  Index-integers (start `i` at 0)
      i<l;i++)           //  Loop (1) from `0` to `l` (exclusive)
    for(j=i;++j<=l;)     //   Inner loop (2) from `i+1` to `l` (inclusive)
      if((t=s.substring(i,j)
                         //    Set `t` to the substring from `i` to `j` (exclusive)
         ).contains(new StringBuffer(t).reverse())
                         //    If this substring is a palindrome,
         &t.length()>1)  //    and it's length is larger than 1:
        r.add(t);        //     Add the String to the Set
                         //   End of inner loop (2) (implicit / single-line body)
                         //  End of loop (1) (implicit / single-line body)
  return r;              //  Return the result-Set
}                        // End of method

JavaScript (ES6), 107 bytes
Returns a Set.
s=>new Set((g=(s,r=[...s].reverse().join``)=>s[1]?(r==s?[s]:[]).concat(g(s.slice(1)),g(r.slice(1))):[])(s))

Test cases

let f =

s=>new Set((g=(s,r=[...s].reverse().join``)=>s[1]?(r==s?[s]:[]).concat(g(s.slice(1)),g(r.slice(1))):[])(s))

console.log([...f('12131331').values()])
console.log([...f('3333').values()])

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Print largest integer you can with the fewest characters
Find a way to output a large integer with few characters. Solutions will be scored based on the magnitude of the number and shortness of code.
EDIT: Let's impose a time limit of a minute on sensible hardware, where sensible is a PC you can buy off the shelves.

So much for Ackerman(9,9) :P

Note that the results highly depend on the output device (/dev/stdout - slowest since it involves graphics, /dev/null - fastest cause it doesn't do anything, | wc -l - medium).

here is a proposed evaluation formula magnitude / (characters^2 * time)

@Shinkirou I would measure my time in decades, so I will get a very huge score :P

print '10' - since you haven't specified the base, this is using base-Graham's Number

As per @Skizz smartass comment, I assume the integer has to consist solely of the digits 0-9 in base 10, so things like the literal strings "9e+999" or "9^9^9" or "Ackerman(9,9)" are out, even though they technically represent integers?

The question should either restrict the size of the code what is the highest number with 100 bytes of code, or enforce a minimum number generate a number, at least 9^1000) as pure digits with as few code as you can. Searching for minimum and maximum the same time would need a conversion function, how to judge on smaller numbers generated with less code, since you cannot ensure that the shortest code will generate the largest number automatically.

It depends on what shelves you have.

Voted to close as not constructive. One year, and still no winning criteria.

JavaScript (10)
alert(1/0)

Prints "Infinity", did I win? :)

Wouldn't alert(Infinity); work too?

But, this is codegolf :P

what about alert('∞') ?

That would be too obvious :) (And that symbol encoded in UTF-8 would need 3 bytes, resulting in the same length)

Prove infinity is an integer :-)

@M28: I thought code golf was about character count, not byte count. ∞ is only one character even if it requires 3 bytes to represent in UTF-8.

I know I'm a bit late to the party... but alert(1/0) works as well and is 10 characters.

That's great, a little late, but I edited my answer, thanks!

@Paul: Chuck Norris counted to infinity, twice. I asked him if it was an integral number and he said: "I don't count fractions, just fractures" I think that proves it.

@Paul typeof(1/0) == typeof(1) :P

@Alpha typeof(1/0) == typeof(1.23) :P

@M28 typeof(1) == typeof(1.23) :P

@kinokijuf typeof null == typeof Math

@Paul the only know person to fit infinity into an integer is Jon Skeet...

bc (1 character)
9

Without a scoring method, this has a fair magnitude/length ratio indeed.

Yikes, downmodded for that.  It was intended as a joke, and yet... come on, please at least explain why you think the reasoning is invalid.

+1 (although 99 has a far better magnitude/length ratio)

Maybe I should say it outright instead of hinting: in its current state the question is subjective and gives us no way to compare answers.

@PeterTaylor while true, 999 is almost 10 times as good.

bash (41)
approx. 10,000,000 digits:
ulimit -t 60;while true;do echo -n 5;done

Can save a few characters there: ulimit -t 60;while :;do printf 5;done (true → :, echo -n → printf).

Python 18 characters
print hex(8**9**9)

It's about 290 million digits.
Turns out python print of decimal numbers is really slow, but hex is fast:
> time python -c "print hex(8**9**9)" | wc
   1       1 290565371
real    0m40.514s

Is that going to run in under a minute? Probably not.

If not, do 888, or 777...

889 takes 13 seconds and is 121 million digits.

Looks like having a power of 2 as the leftmost digit helps a lot, perhaps the python internal implementation of ** takes advantage of sparse bignums.  899 takes just about a minute to compute, 350M digits.

hex is faster because that skips expensive binary->decimal conversions.

Ruby - 8 chars
p $$**$$

260120641601536  digits, today on my system. ($$ is the process ID).

while(1){print 1}

Time to write is O(n) compared to length of output number.

Surely, writing 9 is always going to be better than writing 1, right? Also, Code Golf 101: always strip out all optional spaces. That means all the spaces around the brackets, in this case.

I chose 1 just so it sounds nicer when you read it out loud :-)

@ChrisJester-Young Using 9 may turn in a copyright violation of Revolution 9 from The Beatles. =P

@Alpha numbers cannot be copyrighted

@TheEmptyStringPhotographer True. My comment was made in jest, the last characters are a tongue-out emoji denoting joking. Even if they were, that wouldn't apply here since we're just printing characters on an output stream rather than the recording of the track, so they'd be very different pieces in a non-competing space.

C 86 (including NL)
main(i){
char b[8<<14];
memset(b,'9',8<<14);
for(i=0;i<8<<15;i++)
write(1,b,8<<14);
}

Prints 34_359_973_368 digits on my i7 620M. Challenge this score!
$ gcc -O3 a.c; time ./a.out | wc -c
34359738368

real    0m31.974s
user    0m0.500s
sys     0m41.031s

bash, 35 chars, unimaginably big number
The question doesn't specify the output representation, so I'm going to go charging far past any of the numbers output by previous answers (and way way way past even Graham's number):
for((i=999;i--;))do printf 9→9;done
An even shorter answer, although with a smaller number (still larger than Graham's number) is:
(12 chars)
echo 3→3→3→3

Who downvoted this? And did you downvote the question too? - because if there's a problem it's there, not here.

Mathematica, 5
10! !

10 factorial, factorial.  Prints 22,228,104 digits in about 30 seconds on my machine.

Why not 99! ! ? Same count. Much larger number.

@CMP larger numbers do not print in under a minute, and Mathematica will not even attempt to fully evaluate 99! !.

Sounds fair to me then.

PHP
1,500,050,000,000 digits in 53.383 seconds (1.5 trillion digits) in 61 characters:
$a=bcpow('1000','10000');for($i=0;$i<50000000;$i++)echo $a;

To what medium are you writing this number at a rate of about 26 GB/s?

/dev/null (it is web scale after all).

LISP (18)
10,000,000 digits in few seconds (SBCL).
(expt 10 10000000)

With the same amount of characters, can't you just do (expt 99 99999999)?

Clojure - 28 chars (for unreasonably large numbers)
Strategy is to repeatedly apply the function f(x)=x^x. Works fine because Clojure automatically uses BigInteger arthmetic when this starts to overflow the normal integer range.
(nth(iterate #(expt % %)X)Y)

Choose X and Y depending on how unreasonably large you want the answer to be and how long you want it to run....:
For X=2:
Y=0 -> 2
Y=1 -> 4
Y=2 -> 256
Y=3 -> about 3.2*10^619 (in less than 1ms)
Y=4 -> unreasonably large

For X=9:
Y=0 -> 9
Y=1 -> 387420489
Y=2 -> about 10^320000000
Y=3 -> ermmm..... even bigger than unreasonably large?

A couple of things to note:

(iterate #(expt % %)X) creates an infinite lazy sequence of ridiculously large exponentials. Y just determines which term of the sequence you want to look at (as you can see above, even the very early terms get very large very fast...)
if not already imported you need to (use 'clojure.contrib.math) for the expt function

Bash, 10 characters
seq -s9 $$

2011.8 digits per code character today on my machine.

How does it work? seq --help says: -s, --separator=STRING. $$ is the PID of the current shell. So if it was 3, it would be 19293 - ah - I understand. I would vote it up, if there was an objective winning criteria.

Nice.  Add a -w for an even higher number.... but since there are no winning criteria, it's impossible to know if that's better or worse

Python: 83 characters, 32,089,643 digit number on my PC in a minute
import sys
sys.setrecursionlimit(1e9)
def p(n):sys.stdout.write(str(n));p(n*9)
p(9)

Note that it will either run out of time (in which case kill it) or eventually throw stack overflow errors, so you need to pipe stderr to /dev/null.

Windows PowerShell(7)
I guess this is cheating, but techncially the value printed is an integer:
'9'*9e6

Exactly 9000000 digits.
Can be made larger with (19):
'9'*[int]::MaxValue

but raises an OutOfMemoryException on my poor 32-bit machine. This, however, will work fine as long as it's left running:
for(){write-host -n 9}

PHP, 115 characters:
<? $f=fopen("/tmp/int.txt","w");for($i=$t=0;$i<2.4e7;$i++,$t++){if($t>1e4){fputs($f,$a);$t=0;}$a.=$i;}fputs($f,$a);

Outputs at least 1,024,000,00 characters to /tmp/int.txt.
File size (after running): http://codepad.viper-7.com/rgDglK
Output to Screen, 76 characters
<? for($i=$t=0;$i<2.4e7;$i++,$t++){if($t>1e4){echo $a;$t=0;}$a.=$i;}echo $a;

Has the ability to output 208, 896, 814, 305 characters, tested but unconfirmed through the output.  You can confirm it by only calculating the length of the output through the second link.  Each page may require a few refreshes due to errors.
Output: http://codepad.viper-7.com/rJJerv (Will crash the page eventually)
Length: http://codepad.viper-7.com/zWxX0C
Both the file size verification and the length verification take less than a minute on my old laptop, the output verification crashes the brower ~20 seconds into loading.  The question did not state that the script had to work via command line, so I would not expect it to give perfect results when run that way.

I don't think I can verify your output of 208GB ;)

Modified the code to a verifiable 1GB, it outputs it to a file for verification.

alert(Number.MAX_VALUE); : 1.7976931348623157e+308
<script>function f(m){n=1;for(i=1;i<=m;i++){n*=i;}return n;}alert(f(f(9)));</script> : Infinity

The first isn't an integer and will the second return in 1 minute?

@marcog, what's the fractional part of 1.7976931348623157e+308 ?

time echo "7^7^7" | bc

...
29571409790619889611503701095991663965767866370599610471047901915338\
37220795832889549191447357443319063581523185421788310894001395744859\
694202869611751580402966282378932933502849310357073612870132343

real    0m58.837s
user    0m56.220s
sys 0m0.028s

on a 1.6 Mhz Pentium M.

cat /dev/sda

It's a 256-base Integer with 640,135,028,736 digits on my 640GB hd.
Too bad some are non-printable.

This wouldn't be represented as an Integer and probably not finish wihin 60 seconds.

Hmm, lets see, the largest "decimal number" I could generate
on Linux, 2.4GHz Intel/Core2 w/2GB RAM, needing:
real    0m51.341s
user    0m1.820s
sys     0m5.644s

keeping user time far below 60s.
Perl, 15 characters
print 1,"0"x2e9

gives a number staring with 100000... and with about 2,000,000,000 (2 billion) zeros in total.
Regards
rbo
Tested with
 time perl -e 'print 1,"0"x2e9'>out

on a good hard drive.

You can make it shorter : say"1"x2e9 (10 char).

@M42: Or even say 9x2e9.

@IlmariKaronen: Yes, you're right, and say 9x9e9 produces a longer number.

Ruby - 12 chars
7.5e+306 / character of code
25.7 digits / character of code
p 9e307.to_i

Based on @M28 's answer
PHP 10 chars
echo 9e999

C
printf("-infinity");

What's your definition of "large"?

If you can output a unicode character (wprintf), then just output the '∞' character (U+221E)

What's your definition of "integer"? ;-)

PHP, 18
<?for(;1;print9){}

=D

Notice: Use of undefined constant print9 - assumed 'print9' in Command line code on line 1
Although you'll have to add a space, you can remove the 1 from the foor loop.

Use a semicolon instead. So: <?for(;;print 9);

Ruby, 11
p 9 while 1
Or you can omit the 9 and pretend that it's outputting in the ascii representation of the number "0x0A0A0A0A..."

Haskell (code: 22 chars, output: 309 digits)
main=print$floor 1e309

This outputs:
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
Any higher exponent yields the same result, as 1e309 gets interpreted as Infinity, and this is apperantly the maximum result of floor.

Haskell (20 characters)
main=print.floor$1/0

Factor, 137 characters
USING: calendar kernel io math.order sequences ;
58 seconds hence
99999 "9" <repetition> concat
[ dup write over now after? ] loop 2drop

With comments,
! calendar => seconds hence now
! kernel => dup over loop 2drop
! io => write
! math.order => after?
! sequences => <repetition> concat
USING: calendar kernel io math.order sequences ;

! Push the stop time (58 seconds after now). This leaves 2 extra seconds
! for starting and stopping the script.
58 seconds hence

! Push a long string of "9"s. The best length is near 99999.
99999 "9" <repetition> concat
[
    ! Write the very long string of "9"s.
    dup write
    ! If the stop time is after now, then loop.
    over now after?
] loop

! Empty the data stack.
2drop

This script tries to print as many "9" digits as possible, without exceeding the time limit of one minute. The number of digits changes from run to run.
Output is 10 ^ 4_765_052_349 - 1, if I must display the number in an xterm.
$ time ~/park/factor/factor scratch.factor | tee out
99999999999999999999999999999999999999999999999999999999999999999999999999999999
99999999999999999999999999999999999999999999999999999999999999999999999999999999
...
999999999999999999    0m58.56s real     0m15.63s user     0m26.21s system
$ wc -c out
 4765052349 out

Output is 10 ^ 22_843_571_562 - 1, if I never display the number.
$ time ~/park/factor/factor scratch.factor | wc -c
 22843571562
    0m58.32s real     0m50.27s user     0m19.50s system

Additional notes:

Each write converts the string (Unicode codepoints) to a byte array (UTF-8). This conversion might waste time inside the loop. A faster program might make a byte array before the loop, and write the byte array inside the loop; but I cannot write a byte array to the default output stream, which is a character stream. I would have to use many characters to open a binary stream.
A faster program might call setitimer(2) and handle SIGALRM after 58 seconds. I did not find a short way to call setitimer(2) from Factor.

Brainfuck, 4
Of course the answer is in base 256
-[.]

C-C after a minute. Will print a number about 255^1e10.

Perl 6, 14 bytes
.print for^Inf

There is a pattern in this integer. I would name it a waterfall because it looks like one.

Python, 21 characters
print "10"+"^10"*1337

"output a large integer"

It has 10 to the power of 10 repeated 1336 times (Tetration) number of zeros with a leading 1.

Windows x86 .com
8 bytes
B4 02 B2 39 CD 21 EB F8

Interpreted Haskell using tryhaskell.org, 10 characters, 5120 digits
0xF^0xFFFF

That interpreter seems to truncate the output, which should be the 77076 digits of 15^65535. Notice that 999^999999 also has ten characters and should produce 2999563 digits.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/


text:
Drawing a cube in ASCII art
Task description:
Draw a cube in ASCII art in roughly a cabinet projection.
Monospaced fonts often have characters that are about twice as high as they are wide. Since the input is the length of the vertical lines (excluding the corners), horizontal lines are drawn with twice as many characters so that the resulting image is really roughly a cube. The receding lines are drawn at half the length as mandated by a cabinet projection.
Corners of the cube are represented by +, horizontal lines by -, vertical lines by | and diagonal ones use /.
Summarizing: Let the input be n, then

A horizontal edge of the cube are drawn with - and consists of 2 n characters.
A vertical edge of the cube are drawn with | and consists of n characters.
A diagonal edge of the cube are drawn with / and consists of n/2 characters.
Corners of the cube are drawn with +. Corners are not counted for the length of an edge as detailed above (see examples below as well).

Input:
The input, given on standard input, is a single positive, even number n (2 ≤ n ≤ 30) that gives the length of the vertical lines of the cube. It is followed by a single line break.
Output:
The output is a cube on standard output following above rules. Trailing whitespace on the lines is ignored.
Sample input 1:
2

Sample output 1:
  +----+
 /    /|
+----+ |
|    | +
|    |/
+----+

Sample input 2:
4

Sample output 2:
   +--------+
  /        /|
 /        / |
+--------+  |
|        |  |
|        |  +
|        | /
|        |/
+--------+

ETA: I now accepted the shortest solution. I will update the accepted answer when a shorter one comes along.
Since some people asked how long the entries of our contestants were:

227 – Python
  240 – Perl
  310 – C
  315 – C
  326 – VB.NET
  459 – C

As well as our own solutions (not ranked with the others):

140 – Golfscript
  172 – Ruby
  183 – PowerShell

can you tell as a little about the best solutions you had? How many chars did the smallest have?

@Juan: Added the requested info

Amusingly enough, C++ can use similar drawings as "analog literals": http://hostilefork.com/2009/08/29/tweakinganalog-literals-humor/

@Hostile: Yep, that one was nice, if a bit evil ;-)

Golfscript - 96 chars
~:<2/:$){' '*}:s~'++'<'--'**:^n$,{.$\-s'//'2s<*:&*@s'|':|n}%^$[$s|n|&|]*$s'+'n$,{n'/'@s|&|}%-1%^

Most of the compactness comes from aggressively storing almost everything to a variable (unless you include being written in golfscript).
<    n
$    n/2
s    {' '*}     # top of the stack becomes a string of that many spaces
^    '+------+'
&    '      '   # 2n spaces, i.e. 2s<* or <s2*
|    '|'

A couple of other small tricks here.

'LR''str'* -> 'LstrR'.
Since we need to reverse the order of lines in the last array, we opt to do this after generating the text instead of before. This allows us to save one character because the spaces before the '/' only needs to go past two stack elements (@) instead of 3 (@ .. \).

Python - 248 243 230 227 191
Slightly messy but it basically prints the cube line by line(using a string buffer).
t=v=h=input()/2
s,p,b,f,n=" +|/\n"
l=p+"-"*t*4+p;S=s*4*t;k=s*h;K=b+S+b
r=s*t+s+l+n
while t:r+=s*t+f+S+f+s*(h-t)+b+n;t-=1
r+=l+k+b+n+(K+k+b+n)*(v-1)+K+k+p+n
while v:v-=1;r+=K+s*v+f+n
print r+l

Thanks to @marcog, for pointing out the first line, @ThomasO for pointing out the second line and to @Juan for making me realise I can combine lines.

To save some more space change s=" ";p="+";b="|";f="/";n="\n" to s,p,b,f,n=" +|/\n".

One up vote is not enough. You've pushing me to improve my solution to limits that I thought impossible, thanks :D

:) now to see if better is possible.

Python - 179
h=input()*2
j=d=h/4
q,e,u,p,k="| \n+/"
w=e*d
s=p+'-'*h+p
i=''
o=e+w+s+u
v=q+e*h+q
while j:o+=e*j+k+e*h+k+e*(d-j)+q+u;j-=1;i+=v+e*j+k+u
print o+s+w+q+u+(v+w+q+u)*(d-1)+v+w+p+u+i+s

I'd like to note that I took some ideas from JPvdMerwe (Using a string to print once, and the one-liner for that I didn't know was correct syntax in Python).

Line 3 is missing a 2 at the end, which, unfortunately, pushes up the count to 256.

@JPvdMerwe oops, thanks for catching that!

Maybe you can try caching the results in a string like I did and only print once?

@Juan I think we should avoid keeping old copies in the post, unless the two versions are majorly different. They're viewable in the edit history if someone wants to read it.

@marcog mmm You're right. There's no point to it. Edit coming right up. Maybe we should add a faq with a common format for answers?

@Juan That's a great idea. I'll keep it in mind to post something once we've fleshed out the scope of this site.

As for the FAQ: I often include a length history in my posts ( here was an example that got too long to include, though). Don't know whether such a thing is helpful but it may help others to discover what tricks were used to keep it short. Although I also have a SVN history for that as well.

@Joey version control for golfs! I can't believe I wasn't doing that yet :S

Dang, now you beat me ;-)

@Juan you overcounted by 1 (final EOL is not needed), and you can drop 2 chars by replacing (d-1) with ~-d.

@Juan To drop another byte: e*(d-j) -> w[:-j]

@Juan Yet another byte: w[:-j] -> w[j:]

fortran 77 -- 484 characters
      program z
      read(*,*) i
      g=f('+- ',i/2+1,i,0)
      do k=1,i/2
         g=f('/ |',i/2-k+1,i,k-1)
      end do
      g=f('+-|',0,i,i/2)
      do k=1,i/2-1
         g=f('| |',0,i,i/2)
      end do
      g=f('| +',0,i,i/2)
      do k=1,i/2
         g=f('| /',0,i,i/2-k)
      end do
      g=f('+- ',0,i,0)
      stop
      end
      real function f(c,l,m,n)
      character c(3)
      write(*,*)(' ',j=1,l),c(1),(c(2),j=1,2*m),c(1),(' ',j=1,n),c(3)
      return
      end

No real point in providing a "unobsfucated" version. And note that markdown doesn't get along well with the indent requirements.
I tried fortran because of the inline for loops provided by the write statement. Obviously they help but don't add up to enough to kill the wordiess of the language. It could be reduce by using freeform input.
Validation:
 $ wc cube_func_array.f
 22  41 484 cube_func_array.f
 $ gfortran cube_func_array.f
 $ echo 2 | ./a.out
   +----+
  /    /|
 +----+ |
 |    | +
 |    |/
 +----+
 $ echo 4 | ./a.out
    +--------+
   /        /|
  /        / |
 +--------+  |
 |        |  |
 |        |  +
 |        | /
 |        |/
 +--------+

Thankfully the spec doesn't say what size one should look like:
 $ echo 1 | ./a.out
  +--+
 +--+|
 |  |+
 +--+

but other odd sizes are reasonable:
 $ echo 3 | ./a.out
   +------+
  /      /|
 +------+ |
 |      | +
 |      |/
 +------+

Interesting choice of language :-). Well, size 1 doesn't look too bad. My solution throws up an endless loop. Different rounding behaviors were the reason to throw out odd sizes, if I remember correctly (and the upper bound of 30 for fitting into 80 characters width).

@joey: I do fortran from time to time, and am happy if I'm less than a factor of 10 longer than the winner.

PostScript, 237
[/n(%stdin)(r)file token()/p{print}/r{repeat}([){{( )p}r}/N{n 2 mul}(]){n 2 idiv}/l{N(+)p{(-)p}r(+)p}/I{(|)p}/X{][p}>>begin
( )X l()=]-1 1{dup[(/)p N[(/)p]exch sub[(|)=}for
l(|
)X]1 sub{I N[I(|
)X}r
I N[I(+
)X]-1 1{I N[I 1 sub[(/)=}for
l

History:

2011-03-01 01:54 (427) First attempt.
2011-03-01 02:01 (342) defed a few more things that appeared often.
2011-03-01 02:24 (283) Even more defs.
2011-03-01 02:42 (281) Aaand another def that saves two more bytes.
2011-03-01 03:01 (260) [ and ] have nice properties when used as variables :-). Thanks to KirarinSnow.
2011-03-01 03:12 (246) Inline line breaks, using a dict instead of numerous defs. Thansk again :-).
2011-03-01 03:26 (237) More thanks to KirarinSnow.

My own solution, since it has already been beaten to death by Python:
Windows PowerShell, 183
$t=($w=($s=' ')*($o=($n="$input")/2))*4
$r="|$t|"
$s*($a=$o+1)+($q='+'+'--'*$n+'+')
$o..1|%{$s*--$a+"/$t/$($s*$b++)|"}
"$q$w|"
for(;$o-++$x){"$r$w|"}"$r$w+"
--$b..0|%{$r+$s*$_+'/'}
$q

Ah...languages that let you "multiple" strings by a scalar help for this...

Well, it's still far behind Ventero's Ruby or Golfscript – as usual ;)

Ruby 1.9, 172 165 162 characters
w=(s=?\s)*o=(n=gets.to_i)/2;r=(z=?|)+w*4+z
puts s*(o+1)+q=?++?-*2*n+?+,(l=0...o).map{|u|[s*(o-u),w*4,s*u+z]*?/},q+w+z,[r+w+z]*o-=1,r+w+?+,l.map{|u|r+s*(o-u)+?/},q

Ruby - 423 characters
Really don't want to share this since it's such a horrible count, but since I've written it might as well.
n=$<.read.to_i
a=(q=Array).new(n+n/2+3){q.new(2*n+n/2+3,' ')<<"\n"}
a[n+1][2*n+n/2+2]=a[0][n/2+1]=a[0][2*n+n/2+1]=a[n/2+1][0]=a[n/2+1][2*n]=a[n+n/2+2][0]=a[n+n/2+2][2*n]=:+
a[0][n/2+2,n*2-1]=a[n/2+1][1,n*2-1]=a[n+n/2+2][1,n*2-1]=[:-]*2*n
a[n/2+2,n].each{|b|b[0]=b[2*n+1]=:|}
a[1,n].each{|b|b[2*n+n/2+2]=:|}
c=n/2
a[1,n/2].each{|b|b[c]=b[2+2*n+c-=1]=:/}
c=n/2
a[n+2,n/2].each{|b|b[2+2*n+c-=1]=:/}
a.flatten.each{|g|print g}

Could probably be reduced by quite a bit but I doubt this brute-force approach is going to come anywhere near a decent number of characters so I can't be bothered.

Vyxal J, 61 bytes
½:→›\+?-m:£꘍←ƛ\/?꘍m꘍;Ṙ?ɾv\|?꘍vm¥pJ←ʁ←›v←ȮṘJJ꘍?\|*\++←\/*+f+⁋¥

Try it Online!
This was harder than I thought it'd be. -4 thanks to @AaroneousMiller. Woo, beating ascii-art langs!

61 bytes

PHP, 401 392 382 363 characters:
<? $h=fgets(STDIN);$s="str_repeat";$w=$h*2;$d=$h/2;$b=$h;$c=" ";echo$s($c,$h/2+1)."+".$s("-",$w)."+\n";for($i=1;$i<=$d;$i++,$a=--$b){echo$s($c,($h/2+1)-$i)."/".$s($c,$w)."/".$s($c,$i-1)."|\n";}echo"+".$s("-",$w)."+".$s($c,$d)."|\n";for($i=1;$i<=$h;$i++){echo"|".$s($c,$w)."|";echo $a-->0?$s($c,$b).($a>0?"|":"+")."\n":$s($c,$h-$i)."/\n";}echo"+".$s("-",$w)."+\n";

I originally did this to see how short I could manage to do this in PHP, as I knew that it would be pretty long.  I'm sure it could be reduced, but not by much considering PHP doesn't have many shortcuts.
Validation:

http://codepad.viper-7.com/ftYYz9.php53

Ungolfed Version: http://codepad.viper-7.com/4D3kIA

Just modified it to read from stdin, missed that in the question.  Doesn't need the function anymore because of that.

Modified the code so that it reads from stdin correctly.  Also golfed it a little more to reduce the size.

The lower right diagonal line isn't there and instead an offset vertical line appears. Unless I'm doing something wrong in invoking it, though.

Perl, 163
$d=<>/2;$s=$"x$d;$H=$s x4;$f="|$H|";$t.=$"
x$d--."/$H/".$"x$_."|\n",$m.="$f$s|\n",$b
=$f.$"x$_."/\n$b"for 0..$d-1;$_="+$H+";
y/ /-/;say" $s$_\n$t$_$s|\n$m$f$s+\n$b$_"

Perl 5.10 or later, run with perl -E '<code here>'
Respaced version:
$d = <> / 2;
$s = $" x $d;
$H = $s x 4;
$f = "|$H|";

$t .= $" x $d-- . "/$H/" . $"x$_ . "|\n",
$m .= "$f$s|\n",
$b = $f . $" x $_ . "/\n$b"
  for 0 .. $d-1;

$_ = "+$H+";
y/ /-/;
say " $s$_\n$t$_$s|\n$m$f$s+\n$b$_"

Perl, 269 269 262 256 245 244 237 226 228 224 217 chars

sub p{y/xS/+\//;print;y/+\//xS/}$b=/2;$a=$b;$_=" xx\n";s/ x/  x----/while($a--);until(/^S/){p;s/ [xS]/S /g;s/-x/S|/;y/-/ /}s/ (?= *S)/-/g;y/S/x/;p;y/-x/ |/;p while(--$b);s/.$/x/;while(/ \|/){p;s/..$/S/}y/|S /++-/;p

The basic idea is to do everything with regex substitutions. Because two of the characters used (+ and /) are special characters and turn up a lot in the regexes, it's worthwhile using other characters and substituting them to print.
Slightly more legible version:

# Subroutine to substitute, print, and unsubstitute as described above
sub p{y/xS/+\//;print;y/+\//xS/}
# Read from stdin and set up the initial line
$b=<>/2;$a=$b;$_=" xx\n";
s/ x/  x----/ while($a--);
# Print the top face
until(/^S/) {
  p;
  s/ [xS]/S /g; # First time round: left + -> /; subsequent times move / left
  s/-x/S|/; # Only relevant first time round the loop
  y/-/ / # Only relevant first time round the loop
}
# Prepare and print the line containing second horizontal line
s/ (?= *S)/-/g;
y/S/x/;
p;
# Now print (n-1)/2 identical lines
y/-x/ |/;
p while (--$b);
# Bring the right edge in
s/.$/x/;
while(/ \|/)
{
  p;
  s/..$/S/
}
# Final line
y/|S /++-/;
p

In a sense I'm cheating by using $b as a counter in the intermediate loop - I could instead append whitespace in the loop over $a and then use regex replaces for that loop too - but I'm going to allow that slight deviation from a pure-regex solution.
No doubt some scary person can turn this into a much shorter sed script.

"Slightly more legible version" - gotta love that Perl only becomes slightly more readable when newlines and whitespace are included. :)

@Steve, even with the comments you have to know a bit of Perl to understand it. Using y for tr isn't obvious, and as for the way "while" can go before or after...

Lua, 294 302 292 bytes
Golfed:
n=(...)p="+"d=2*n s=" "S=s:rep(d)h=n/2 T=s:rep(h)L="\n"o="/"v="|"a=p..("-"):rep(d)..p r=T..s..a..L for i=0,h-1 do r=r..s:rep(h-i)..o..S..o..s:rep(i)..v..L end r=r..a..T..v for i=1,h do r=r..L..v..S..v..T..(i==h and p or v) end for i=h-1,0,-1 do r=r..L..v..S..v..s:rep(i)..o end print(r..L..a)

Ungolfed:
n        = n or io.read() or 6
plus     = "+"
doubled  = 2*n
space    = " "
Space    = space:rep(doubled)
halved   = n/2
T        = space:rep(halved)
Line     = "\n"
or_sign  = "/"
vertical = "|"
a        = plus..("-"):rep(doubled)..plus
result   = T..space..a..Line

for i=0,halved-1 do
    result = result .. space:rep(halved-i) .. or_sign .. Space .. or_sign .. space:rep(i) .. vertical .. Line
end

result = result..a..T..vertical

for i=1,halved do
    result = result .. Line .. vertical .. Space .. vertical .. T .. (i==halved and plus or vertical)
end

for i=halved-1,0,-1 do
    result = result .. Line .. vertical .. Space .. vertical .. space:rep(i) .. or_sign
end

print(result .. Line .. a)

Input is given on the standard input stream. This doesn't seem to work here.

You can also leave out the or 6 after the read() call, which saves four bytes :-)

Hm, now with the (...) it doesn't work for me anymore on Lua 5.1.4.

Canvas, 63 bytes
╴»
±╵⁷／╋╴«３＋⁷
-×+×║⌐１╴├╋；⁷├⁷±╋２⁷⁸⁸├⁷／╋１２╴«├２⁷５×３＋⁷±╵⁰２ｎ｛┤╴|＊+∔╋

Try it here!

Vyxal, 40 bytes
½"‛|/f*?d¤-JǏz:Yf:@2+$¤p\+jǏ»×g=↔F»8τ„ø∧

Try it Online!
     f*                                  # Repeat each character of
  ‛|/                                    # "|/"
½"                                       # by each of [input, input/2]
          -                              # Append
       ?d                                # 2*input hyphens
         ¤                               # To the empty string
           J                             # Add that to the list
            Ǐz                           # Get all pairs
              :Yf                        # Double each pair
                                      ø∧ # Draw on canvas with
                 :@                      # Lengths: length of each of that
                   2+                    # + 2
                     $                   # String: That
                        \+j              # Joined by "+"
                      ¤p   Ǐ             # With a + at the start and end
                            »×g=↔F»      # Directions: compressed number
                                   8τ„   # Converted from base 8 to [4, 1, 0, 5, 1, 6, 5, 2, 6, 4, 2, 0]