Joe's Tricks
-
Response files, command line option @<respfilename>.rsp, can be used to hold assembly references, freeing you from typing them on the command line. The C# compiler automatically calls the response file at
-
Using the as operator is more efficient than the is operator when obtaining a reference to an object and checking its type at the same time. More specifically, the following operation using the is operator
-
Implement the using statement with the Dispose pattern for deterministic resource destruction. This allows you to free system resources when youre done with them rather than waiting for the garbage collector, which may never finalize the object holding the resources.
-
When implementing a method that accepts a variable number of parameters, use the params parameter type. It accepts a comma-separated list of arguments, a single dimension array, or a jagged array.
-
For late bound delegates, instantiate the delegate in the get accessor of a static property. This ensures that the delegate is not created until its used, saving system resources. This technique is shown below:
-
Explicitly declare base class methods as virtual if you intend for subclasses to override them. Otherwise, non-virtual base class methods will be hidden by derived methods of the same name. The virtual modifier guarantees the ability to implement polymorphic behavior.
-
C# doesnt have automatic fall through on switch statements without break statements between cases. To simulate fall through in a switch statement, similar to the behavior of C and C++ switch statements, use goto case n:, where n represents the next case statement.
-
When the value of a variable isnt known until runtime and you still want to implement constant behavior, use the readonly modifier. It can be initialized in a constructor, but cant change thereafter.
-
A property with only a get accessor
-
Conditions for if and loop statements must evaluate to a Boolean true or false value. To simulate a Boolean false with an integral expression use
%windir%\Microsoft.NET\Framework\v<version#>\csc.rsp.
This file contains all of the .NET assemblies, leaving only third-party and project assemblies to be added to a local response file.
if (mc1 is MyClass) { mc2 = mc1; } else { mc2 = null; } }
takes two operations: one to check if mc1 is of type MyClass and another to assign mc1 to mc2. The next line shows how the as operator performs this in one statement, leaving a null result if mc3 is not of type MyClass:
MyClass mc3 = mc1 as MyClass;
public delegate void MyDelegate(); public static void MyMethod() {} public static MyDelegate MyCallBack { get { return new MyDelegate(MyMethod); } }
public string MyReadProp { get { return "readonly"; } }
is read-only, and a property with only a set accessor
public string MyWriteProp { set { myField = value; } }
is write-only.
if ( ( int_expression ) == 0 ) { }
and to simulate a Booleantrue condition use
if ( ( int_expression ) == 0 ) { }