Podcast #128: We chat with Kent C Dodds about why he loves React and discuss what life was like in the dark days before Git. Listen now.

Hot answers tagged

31

Here, another try: class Foo { //static Foo foo = new Foo(); // you are not allowed using this approach //static readonly Foo foo = new Foo(); // you are not allowed using this approach Foo foo = new Foo(); MWAHAHAHA, THIS LINE GIVES A COMPILE ERROR! NO STACKOVERFLOW EXCEPTION ANYMORE! LOL } class Program { static void Main(string[] args)...


28

Yay, found it! public class Animal { public class Giraffe { } // 1 } public class Giraffe : Animal // 2 { public bool Test() { return this is Giraffe; } } Since Giraffe 1 is a member of Animal, and Giraffe 2 is one level further out, the name Giraffe in the is test refers to the former (section 7.6.2 in the C# 5 spec). Visual ...


25

How about this? class Foo { //static Foo foo = new Foo(); // you are not allowed using this approach //static readonly Foo foo = new Foo(); // you are not allowed using this approach String str = @" Foo foo = new Foo(); "; } class Program { static void Main(string[] args) { new Foo(); } }


24

C#, 46 (88 including boilerplate) using System;class P{static void Main(){ try { while(true) try { System.Threading.Thread.CurrentThread.Abort(); } catch(Exception ex2) { } } catch(Exception ex1) { // your goal ...


21

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;


20

C# 24 Characters terminates the inner try block before intended, allowing me to cause an exception outside of the try block. }finally{int a=1/0;}try{


20

static void Main(string[] args) { bool a, b; unsafe { int* pa = (int*)&a; int* pb = (int*)&b; *pa = 1; *pb = 2; } Console.Write(Test(a, b)); } This prints True for me with the C# implementation that comes with Visual Studio 2015. I actually don't know any C#, but I figured I'd try to write ...


17

52 characters }static Program(){System.Console.Write(0<1);for(;;); so the whole thing becomes: class Program { static void Main() { System.Console.Write( "False" ); } static Program() { System.Console.Write( 0 < 1 ); for ( ; ; ) ; } }


15

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


15

C# 85 chars class H{static void Main(){if(System.Console.Out.WriteAsync("Hello, world!")is H){}}}


14

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


14

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


14

Ummm, simply provide an implementation of AssertTrue that doesn't throw anything? void addOne(int a){} void AssertTrue(bool b) { } You never specified what testing framework is used here. It looks like MSTest, but I fired up a new test project and AssertTrue doesn't exist, so I took the liberty of implementing it myself. EDIT This solution might be what ...


14

class Foo { public class Bar { Foo foo = new Foo(); } } class Program { static void Main(string[] args) { new Foo(); } } I don't have a C# compiler at hand, but I suspect this might work. The idea is to put the definition in a nested class, such that foo would only be assigned if an instance of Bar is created. Now, ...


13

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


13

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


13

Java, 76 or 31 Counting only the insertions made to the code, ignoring new lines. 76 if you count everything I've added, 31 if you exclude the first line and the last line, i.e. only counting int a=1/0;try{}catch(Error e){}. class P{public static void main(String[]A){ try { while(true) try { int a=1/0;try{ } ...


12

C# (114) class M{static void Main(){if(typeof(System.Console).GetMethods()[78].Invoke(null,new[]{"Hello, world!"})is M){}}} Note that the proper index for Write(string)/WriteLine(string) may be different on your system. However, since there are only 106 methods total, I'm almost certain either Write(string) or WriteLine(string) will be a two-digit index ...


12

C#, 76 class X{static void Main(){if(System.Console.Write("Hello, World!")is X){}}} I tried this in my VS2012 and it works just fine, even though it is quite a surprise that you can apply the is operator to void...


11

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


10

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


10

Toggle commented out blocks by adding/removing the last slash on the first line: /**/ code block A /*/ code block B /**/ Bonus solution, toggle this one by adding/removing the first slash on the first line: //* code block A /*/ code block B /**/


10

28 bytes You can make your last approach a bit shorter by replacing the '0' by 48. You can also strip all unnecessary spaces and use 1-char variable names (for example, number -> n): n.Select(i=>i-48).ToArray();


9

Never wrote C# before, does this work ? class Foo { Foo fooExit = exitMe(); //static Foo foo = new Foo(); // you are not allowed using this approach //static readonly Foo foo = new Foo(); // you are not allowed using this approach Foo foo = new Foo(); static Foo exitMe() { System.Environment.Exit(0); return null; ...


8

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


8

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.


8

115 Bytes class H{static void Main(){if(((System.Action)(()=>System.Console.Write("Hello, world!"))).DynamicInvoke()is H){}}} It's likely possible to produce something a bit shorter, but I'm pretty sure that you're going to need make some sort of asynchronous call.


8

class Foo { Foo(bool recursion = false) { if (recursion) Foo foo = new Foo(); } } class Program { static void Main(string[] args) { new Foo(); } }


8

To simplify Florent's code: class Foo { Foo foo = new Foo(); static Foo() { System.Environment.Exit(1); } }


7

C#, 51 characters Console.Write("\b\b\b\b\b");Console.Write("True "); Will only work on standard output


Only top voted, non community-wiki answers of a minimum length are eligible