Effective C#: 50 Specific Ways to Improve Your C#

Author: Bill Wagner
All Stack Overflow 19
This Month Stack Overflow 1


by anonymous   2019-01-13


You can use one of the following—

1: Conditional attribute

The Conditional attribute indicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined.

Code example:

static void Method() { } 

2: #if preprocessor directive

When the C# compiler encounters an #if preprocessor directive, followed eventually by an #endif directive, it compiles the code between the directives only if the specified symbol is defined. Unlike C and C++, you cannot assign a numeric value to a symbol. The #if statement in C# is Boolean and only tests whether the symbol has been defined or not.

Code example:

    static int testCounter = 0;

3: Debug.Write methods

Debug.Write (and Debug.WriteLine) writes information about the debug to the trace listeners in the Listeners collection.

See also Debug.WriteIf and Debug.WriteLineIf.

Code example:

Debug.Write("Something to write in Output window.");


Beware of using #if directive since it can produce unintended situations in Release build. For example, see:

    string sth = null;
    sth = "oh, hi!";

In this case, non-Debug build will print a blank message. But, this potentially may raise NullReferenceException in a different case.

Read more

See also

There is also a tool, DebugView, which allow to capture debug information from external applications.

by pbz   2017-08-20

I would recommend Effective C# by Bill Wagner (first edition and second edition). He goes through a number of language constructs and techniques and explains which ones are faster and why. He touches on a lot of best practices as well.

More often than not, however, optimizing your algorithm will give you far better results than using any kind of language / optimization technique.

by anonymous   2017-08-20

How about Effective C#?

by anonymous   2017-08-20

Bill Wagner has a chapter about this in his book "effective c#" (http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660). He concludes by using the following principle:

  1. Is the main responsability of the type data storage?
  2. Is its public interface defined entirely by properties that access or modify its data members?
  3. Are you sure your type will never have subclasses?
  4. Are you sure your type will never be treated polymorphically?

If you answer 'yes' to all 4 questions: use a struct. Otherwise, use a class.