Sunday, May 17, 2009

Optimize C# Code... 2

Optimize C# Code... 2

Code optimization is an important aspect of writing an efficient C# application. The following tips will help you increase the speed and efficiency of your C# code and applications.

1. Use of the operator ?: and ??

The conditional operator ?: returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form:

condition ? first_expression : second_expression;

If condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.


if(i == 0) str = "Zero" else str = "Non Zero";


using the conditional operator, it will be as follow:


string str = x == 0 ? "Zero" : "Non Zero";


The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types.
It returns the left-hand operand if it is not null; otherwise it returns the right operand.


if (string.IsNullOrEmpty(str))
newstr = "i don't wanna be null"
else
newstr = str;



using the conditional operator, it will be as follow:


string newstr = str ?? "i don't wanna be null";


2. TryParse and Parse
The big difference between TryParse and Parse, is that the first one will return a boolean value, indicating if the conversion was successfull or not, and the second one will give you an exception if the convertion was not possible.


string AreYouADeveloper = "true"

if (bool.TryParse(AreYouADeveloper, out boolValue))
{
MessageBox.Show("welcome developer guy")
}
else
{
MessageBox.Show("You Are Not a Developer")
}



3. Exceptions cause performance to suffer significantly
Since exceptions cause performance to suffer significantly, you should never use them as a way to control normal program flow, so the best way is to write code that avoids exceptions. If it is possible to detect in code a condition that would cause an exception, do so. Do not catch the exception itself before you handle that condition.

4. .Net System.Diagnostics.DebuggerStepThrough Attribute
Sometimes when you are running your code in debug mode, you don't want to stop in some methods, maybe because you already know that this method will always return what you want, because is not so important for the job you have in hands, or some other reasons... That's where the DebuggerStepThrough comes in. The compiler will add the necessary metadata preventing the debugger to step into the method. Even if you have this attribute defined, you can stop in, if you define a breakpoint there.


public string Name
{
[System.Diagnostics.DebuggerStepThrough]
get { return name; }
}

0 comments: