Saturday, January 31, 2015

Welcome to JetBrains .NET Tools Support site!


Before you submit a question, please take a look at Frequently Asked Questions and Knowledge Base for JetBrains dotTrace, dotCover, dotMemory and dotPeek.
For quick results, you can use the Knowledge Base Search below.
If you haven't found an answer to your question in our FAQ and KB, please click 'Submit a request' in the top menu to submit a new support ticket.
If you'd like to visit JetBrains ReSharper Support Site, please use this link: http://resharper-support.jetbrains.com.

Friday, January 30, 2015

Top 20 Programming tips for Performance Improvement (Java/C#)

Many architects and developer are concerned about the performance of their application, but it is quite easy to write reliable and high-performance applications. This article show twenty short aspects that have to be concerned designing and written a managed language like Java/C# . The twenty points are not ordered by priority.
Note 
This article was originally targeted for JAVA language but all the thoughts presented here is applicable to C# as both share same school of thought (Managed Memory Model)
1. Avoid producing a lot of garbage
The Java/C# memory management is quite simple. The memory can be allocated in a program and when that memory is no longer referenced, it is garbage collected. You don’t have to care about these aspects. Theoretically, the garbage collector is executed only when the system load is low, and it is not supposed to affect an application. In real life a heavy used application can become very slow and the run of the garbage collector has an impact.

Always try to avoid generating garbage, because this will reduce the need to run a garbage collection. Just think about three things:
  1. Reuse existing objects
  2. Avoid creating unnecessary objects
  3. Create object pools (Use Object Pool only when object creation is very expensive like threads or data connection, )[Refer Comment Below]
2. Avoid using finalizers when possible
Whenever an object finalizer needs to be executed, it gets placed into a finalization queue. On most systems, this queue will be run only when a first level garbage collection fails. First level garbage collection only fails when room for a new object cannot be found in the heap or the overall free heap space drops below 25%. This behavior causes all the resources associated with that object to be retained until that time, which can be many garbage collection cycles later. This time delay between queuing a finalizer and actually running the finalizer can be considerable, causing potential shortages of system resources. Not using a finalizer on the object will avoid this delay.

3. Recycle and/ or cache objects
The cost of object creation and garbage collection is quite high. If existing objects can be reused, then savings in memory and runtime performance can be realized. Look for opportunities in writing code where existing objects can be reused and recycled instead of creating new ones. Cache objects in frequently used methods so that they will persist between calls, but make sure that the cached object’s state is set properly before subsequent use. For example, if you cached a date object, then prior to using it again, ensure that it is set to the proper date. Some objects are not as straightforward as a date object, so use care.
4. Variables
In contrast to a compiled language such as C++, application performance in Java is noticeably affected by what types of variables are accessed and how they are accessed. For example, while stack variables are directly addressable (and may even be placed in registers), instance variables typically require an extra level of indirection to be accessed.

This implies the potential value of data location shifting, changing the storage location of data based on the access patterns. For example, a data-intensive operation would benefit from first copying instance variables into stack variables, operating on the stack variables, and, finally, copying the stack variables back to the permanent instance variables.

This technique is particularly useful when a method variable is accessed repeatedly within a loop. For example, the common loop construct:

for (int i = 0; ++ i <= limit; )
can be improved by 25 percent (5 percent with a JIT compiler) by rewriting it as:

for (int i = limit; -- i >= 0; )
to reduce the number of accesses to the limit variable.

5. Reduce class hierarchy
In general, object creation gets slower as the class hierarchy grows deeper. In addition, a class hierarchy with a longer depth can causes longer load time of the applet because additional classes must be transferred across the network. You should avoid, when possible, specializing for minor variations that could otherwise be represented by a state variable. However, this must be done with care as it might sacrifice the object-oriented design of the application.

6. Avoid explicitly calling the Garbage Collector
Invoking garbage collection when responsiveness is expected, (e.g. when processing a mouse button event) can slow the program down at a time when the user is expecting fast processing. In most circumstances, invoking System.gc()explicitly will not be needed. Invoking System.gc() will not run the Garbage Collector at once, it just says that the Garbage Collector will run next time the system has time to run the Garbage Collector.

7. Avoid synchronization
The JVM uses class locks while resolving class references. Class references are resolved on an as used basis (versus resolving at class load time) so it is not easy to predict when the JVM will want a class lock. So, do not synchronize on a class.

An alternate approach would be to create a special purpose lock object instead. For example:

private static final Object lock = new Object();

However, synchronization activity can consume significant system resources and affect Java performance. This may be true even if there is only one thread being executed, due to constant checking of lock availability. As a result, synchronization should be reduced as much as possible.

8. Use Lazy Evaluation
Any large application or general purpose framework is likely to have a relatively significant amount of static data around behind the scenes. One way to initialize such data is to use static class initialization blocks. This mechanism is simple and supported by the Java language. However, it can increase an application’s load time, since all such initialization is done before the application starts, even if it is not needed until hours later (or perhaps never needed during a particular run of the application.)

Lazy evaluation is a reliable and much used mechanism for deferring initialization of static data until it is actually needed. So any data never used is never created, and any data not actually needed to bootstrap a subsystem does not place a startup time burden on its client applications.

In object oriented languages, lazy evaluation is quite easy to implement. You merely make your data private and provide a public getter method (something you would want to do anyway.) Since any access to the data is through the getter, it can allocate the object upon demand. This does imply the need for some synchronization, i.e. you must make sure that two threads don’t simultaneously try to create the static object. This is easily done through a synchronized code block that does the actual object creation.

The minimum synchronization overhead can be obtained by first checking the static reference for null and only entering the synchronized block if it is still null. A subsequent check is still required after entering the block to insure that another thread has not already created the object. But, once the object actually gets created, the only performance overhead imposed is that of a null reference check on each subsequent entry to the getter.

To do the synchronization, the class’ class member is used since it’s a static object that is already available to us. This avoids a bootstrapping issue of having to synchronize in order to create an object in order to synchronize the creation of an object, etc...

Another aspect of lazy evaluation involves complex, usually tabbed, GUI objects. Where possible, only immediately create the components that are initially visible to the user then create the others either in the background or upon their coming into view. This strategy will increase the perceived performance of the application by displaying the relevant information as soon as possible, and will often save on memory overhead if the user never even accesses the other components.

9. Optimized classes
Well written Java applications can suffer performance degradation when inappropriate classes are used. For instance, standard Java class libraries rely on general purpose interfaces to hide underlying implementation details. While modular, generic implementations may limit overall library performance.

An example of this is the interaction between the ByteArrayOutputStream and DataOutputStream classes. ByteArrayOutputStream encapsulates the writing of bytes into a byte array. DataOuputStream serializes high level Java built-in types (int, long, float, String, etc.) to an object exposing the OutputStream interface. However, as it is used to support a variety of output media including files , TCP/IP connections, and memory buffers, the OutputStream interface only allows one byte of data to be output at a time (via a synchronized method). When the DataOuputStream is attached to ByteArrayOutputStream, performance is sub-optimal as data is only produced one byte at a time (through the OutputStream interface). To output each byte, the DataOuputStream incurs the overhead of calling a synchronized method, checking for array overflow, copying the output byte into the byte array, and incrementing the output byte counter.

To achieve optimal performance, an optimized class could be implemented to merge the functionality of the ByteArrayOutputStream and DataOutputStream classes. To place data into a byte array, the optimized class simply copies the data into the buffer, checking the array bounds and incrementing the byte counter only once for each data item output. For applications that do not require synchronized access to the stream, the methods in the optimized class can be asynchronized to further boost performance.

10. Use StringBuffer /StringBuilder
Since strings are immutable, any change to a string will create at least one more string object. This degrades performance and unnecessarily creates objects that will eventually need to be garbage collected. StringBuffers, however, are modifiable and can be used to avoid creating temporary String objects.

StringBuilder are more advance API written on  the top of StringBuffer can also be used for the same purpose [See comment below]

11. Explicitly close resources
When using the FileInputStream method, do not rely on the object finalizer to close the file for you. Explicitly close the file when you are done. The problem with allowing the finalizer to close the file is there is a potentially long delay before the finalizers are actually run. This will keep the operating system file handle in use until the time the finalizers do run potentially creating a situation where the pool of operating system file handles become exhausted. Explicitly closing the file will cause the file handle to be released immediately.

12. Limit number of threads

Every java thread created requires dedicated memory for its’ native stack frame. On many systems, the size of this native stack frame is controlled by the -ss Java command line parameter and is the same for every Java thread crea ted. The default stack size on some platforms is as much as 32 kilobytes. For an application that has 20 threads this represents 32KB*20 or 640KB. Limiting the number of threads in the application will help reduce the system memory requirements. It may also improve performance by giving more CPU time to threads doing real work.

13. JDBC Data Access
When using the ResultSet.getXXX methods in JDBC make sure that the get call you use is the of the same type as the way the data is stored in the database. So, if there are integers in the database, please use the ResultSet.getInt() method to read it from the result set.

14. Using JNI
When using JNI and you need to get a member of a primitive array object (from C to JAVA) then use the Get<PrimitiveType>ArrayRegion call instead of the Get<PrimitiveType>Array calls.

Group native operations to reduce the number of JNI calls.

Consider consolidating transactions or operations to minimize the number of JNI calls needed to accomplish a task. Reducing the number of times the JNI overhead needs to be paid will improve performance.

15. Avoid excessive writing to the Java console

Writing information to the java console takes time and resources, and should not be done unless necessary. Although helpful in debugging, writing to the console usually involves a great deal of string manipulations, text formatting, and output. These are typically slow operations. Even when the console is not displayed, performance can be adversely affected.

16. Data Types
Primitive types are faster than classes encapsulating types. Avoid the costs of object creation and manipulation by using primitive types for variables when prudent. Memory can be reduced and variable access times can be improved.

In the following example, the second declaration is smaller and quicker:

Currency {
public double amount;
}
double currency_amount;

Unlike C++, casting in Java is not done at compile time. Since there is a cost at run-time, avoid unnecessary recasting of variables.

Use int instead of long when possible on 32-bit systems.

long is 64-bit while int is 32-bit data type. 32-bit operations are executed faster than 64-bit on 32-bit systems. Example 1 took about half of the time of Example 2. It is worthwhile noting that Example 2 will run faster on systems with 64-bit addressing.

Use static final when creating constants. When data is invariant, declare it as static and final. By reducing the number of times variables need to be initialized and giving better optimization information to the JVM, performance can be improved.

17. When possible, declare methods as final
Declare methods as final whenever possible. Final methods can be handled better by the JVM, leading to improved performance. In this example, the second method will execute faster than the first one.

void doThing(){
for (int i=0; i<100; ++i){
dosomething;
}

}
final void doThingfinal(){
for (int i=0; i<100; ++i){
dosomething;
}
}

18. Arrays are faster than Vectors
By avoiding vectors when arrays will suffice, application performance can be improved. If you use a vector, remember that it is faster to add or delete items from the end of the vector.

19. Do not overuse instance variables
Performance can be improved by using local variables. The code in example 1 will execute faster than the code in Example 2.

Example1:

public void loop() {
     int j = 0;
     for ( int i = 0; i<250000;i++){
     j = j + 1;
     }
}

Example 2:

int i;
public void loop() {
    int j = 0;
    for (i = 0; i<250000;i++){
    j = j + 1;
  }
}

20. Know when to use immutable objects
There are many valid reasons to use immutable objects. "The main disadvantage of immutable objects can be performance, so it is important to know when and where to use them.

The Java API provides two very similar classes, one immutable and one mutable. String was designed to be immutable, and thus simpler and safer. StringBuffer was designed to be mutable, with tremendous advantages in performance. For example, look at the following code, where one uses string concatenation and the other uses the StringBuffer append method. (The doSomething() method is overloaded to take characters as either String or StringBuffer.)

Case 1

for (i = 0; i < source.length; ++i) {
doSomething(i + ": " + source[i]);
}

Case 2

StringBuffer temp = new StringBuffer();
for (i = 0; i < source.length; ++i) {
temp.setLength(0); // clear previous contents
temp.append(i).append(": ").append(source[i]);
doSomething(temp);
}

Behind your back, the compiler will optimize Case 1, but it still involves the creation of two objects per iteration. Case 2, on the other hand, avoids any object creation. Because of this, Case 2 can be over 1000% faster than Case 1 (depending on your JIT, of course).

14 C# Tips that improve code efficiency and productivity

C# is a wonderful programming language; I’ve been writing windows apps and working with C# since C# 2.0 and I like it. The C# syntax in general is very straight forward and simple, in addition, I also like the fact that despite the constantly expanding code library, things are still kept readable. Below I have listed 14 tips that you can use to improve code efficiency, make your code more compact and achieve productivity. I have no doubt that you know or use one or more already.

1. Ternary Operator (?:)

I first time read about the ternary operator while I was browsing the list of operators in C# back in 2006, it’s an interesting operator and I still use it today in programming tasks. The ternary operator is very straight forward and simple to understand—I’ll give you a few examples to clear up things and make sure you understand this.
1.1 string IsEligibleToPurchaseAlcohol(int age)
I’ve written a function which prints out a string, based on the age value the user enters. I’ve followed the alcohol laws of the United States, this means that there is a law for alcohol minimum purchase age; you have to be 21 or over to be eligible to buy alcohol. Here’s the code written with If-then-else:
string IsEligibleToPurchaseAlcohol(int age)
{
   string message = null;

   if (age >= 21)
   {
        message = "Congratulations! You are eligible to buy alcohol.";
   }
   else
   {
        message = "Sorry! You're not eligible to buy alcohol.";
   }
   
   return message; 
}
And here is the code written in one single return line using the ternary operator, notice that both functions complete the same check.
string IsEligibleToPurchaseAlcohol(int age)
{
    return age >= 21 ? "Congratulations! You are eligible to buy alcohol." : 
                       "Sorry! You're not eligible to buy alcohol.";
} 
1.2 string PMorAM()
In this second example, I am using the ternary operator to determine if it is PM or AM, and return that in a string with current time + “PM” or “AM”.
string PMorAM()
{
    return string.Format("{0}:{1} {2}", DateTime.Now.Hour, 
         DateTime.Now.Minute, DateTime.Now.Hour >= 12 ? "PM" : "AM"); 
}
1.3 bool Is18(int age)
In this third example, I am using the ternary operator to determine if the user is 18 years old or younger, and returntrue or false.
bool Is18(int age)
{
    return age == 18 ? true : false; 
}

2. Null-Coalesce Operator (??)

Every time we need to test for null values in our code, the null-coalesce operator (??) becomes handy to use. I’ve created 3 code-snippets below, just to demonstrate code efficiency and to show how much shorter the code can become.
2.1 The regular newbie way of testing for null value
object a = null;
object b = new object();
object c;

if (a != null)
    c = a;
else
    c = b; 
It is very obvious that a C# developer that has just learned to use the ternary operator will rewrite this to a single line.
2.2 Using the ternary operator to test null
object a = null;
object b = new object();
object c = (a != null) ? a : b; 
With the null-coalescing operator we can make this shorter. If the left-hand side equals null, the right-hand side will be assigned, in this context object b.
2.3 Using the null-coalescing operator to test null
object a = null;
object b = new object();
object c = a ?? b;

3. Boolean

The Boolean (a.k.a. bool) is a data type that supports two states, true/false. The bool data type is commonly used to determine whether a return value is true or false, as we saw with the third example in the examples that use the ternary operator. To explain what code efficiency one can gain by just using bool in if-statements and return values, I’ve written some examples below.
3.1 If-else statement
To be more correct, and more efficient one does not need to fix check whether a method will be true or false, only invoke the method name inside the if-statement, and the rest of the check will occur automatically.
if (IndividualsNormalAge() == true)
{
    System.Diagnostics.Debug.Print("Yes!"); 
}
else
{
    System.Diagnostics.Debug.Print("No!"); 
}
To make this more efficient, simply remove == true, and it will be determined autormatically.
if (IndividualsNormalAge())
{
    System.Diagnostics.Debug.Print("Yes!"); 
}
else
{
    System.Diagnostics.Debug.Print("No!"); 
}
3.2 Return
In some cases one does not need to use the ternary operator to return true/false, that’s how simple it is, below I have a few code-snippets:
bool IndividualsNormalAge()
{
    Random r = new Random(); 
    int age = r.Next(1, 113); 
    return (age < 111) ? true : false; 
}
The ? true : false can be removed, and it will still return true/false.
bool IndividualsNormalAge()
{
    Random r = new Random(); 
    int age = r.Next(1, 113); 
    return (age < 111); 
}
It is very easy to understand this, to clarify further, I've added two more code-snippets below:
return (i == 1) ? true : false;
and even shorter:
return (i == 1); // Returns true only if i equals 1

4. Is String Null?

The string.IsNullOrEmpty tests strings by checking for string references that are null, or empty strings. In short, the static method IsNullOrEmpty enables you to simultaneously test whether a String is null or its value is Empty—as tested in the code-snippet below:
if (string.IsNullOrEmpty(s))
    return "This string is null or empty.";
else
    return string.Format("This string is not null or empty, it equals to \"{0}\" ", s);

5. Data Type Conversion

It's very common that we sometimes or very often have to convert data types for various of reasons, for instance, if the we have a decimal variable with a set value, and we want to convert it into an Integer or int an explicit conversion will be performed to achieve this.
int j = 0;
decimal money = 9500.34m;

j = (int)money; // An explicit conversion using cast operator.
The better option is to use the Convert class which supports full Data Type conversion between all data types.
int money = 0; 
string uservalue = null;

uservalue = Console.ReadLine();
money = Convert.ToInt32(uservalue); 
In the first code-snippet we do explicit conversion using a cast operator, and in the second code-snippet we use the Convert class and invoke the ToInt32() method to convert a string to an int. Is there any difference? Yes, of course there's a difference between the first code-snippet and the second code-snippet—I'll explain, explicit conversions strictly requires a cast operator, and that the source and destination variables are compatible. Conversion using a helper class such as Convert allows us to convert between non-compatible types and does not require the use of cast operator, thus, providing a safe conversion method with performance benefits.

6. Using Statement

Allocation of memory is as important as freeing memory. However, in C# we have the Garbage Collector (GC) which takes care of a lot, but some classes in the .NET library implement the IDisposable interface,
and these require manual object disposal. In the code-snippet below, we make a new instance of the SHA1 class, and in the finally code-block we dispose the object.
SHA1 sha1 = SHA1.Create(); 
            
try
{
   StringBuilder sb = new StringBuilder();
   byte[] data = Encoding.UTF8.GetBytes(text);
   byte[] hash = sha1.ComputeHash(data);

   foreach (byte b in hash)
   {
       sb.Append(b.ToString("x2").ToLower());
   }

   hashed = sb.ToString();
}
finally
{
    if (sha1 != null)
        ((IDisposable)sha1).Dispose();
}
A better way is to use the using statement once, as shown below:
// Allocate
using (System.Security.Cryptography.SHA1 sha1 
    = System.Security.Cryptography.SHA1.Create())
{
     //Use the sha1 to computer the hash.
     //sha1 can only be used inside this code-block
}
//Automatically Disposed
In the second code-snippet, using (...) { ... } will only allow the usage of an object once within the curly braces ("{}"), and disposal will happen automatically after the last curly brace. This approach is much better, especially, if we only need to use one class once.

7. Properties

Prior to C# 2.0, programmers used to solve things very differently, see the first code-snippet:
class Child
{
    public Child() { }

    private int age = 0;

    public int GetAge() { return age; }
    public void SetAge(int _age) { age = _age; }
}
In the first code-snippet, a programmer in C# 1.0 was required to write two methods to be able to set and get a value, in this context, the age of a child. However, that's a lot of code, and it quickly gets messy and it's not elegant enough. However, this issue was solved in C# 2.0 with the introduction of Properties. The code-snippet below demonstrates Properties.
class Child
{
    public Child() { }
      
    private int _age = 0;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    } 
}
The Properties are really useful, especially when we need to protect internal variables and not expose them to the outside world. The second code-snippet above clearly protects our internal variable, _age. However, even the second code-snippet isn't elegant enough, what's elegant is the last code-snippet below. Yes, only get; set; —this is an auto-implemented property (called auto-implemented properties) introduced in C# 3.0.
class Child
{
    public Child() { }
    public int Age { get; set; }
}
The last code-snippet is cleaner, safer and more concise since no additional logic is required in the property accessors, in short, more code efficiency benefits.

8. Namespace Alias Qualifier

The Namespace Alias Qualifier (a.k.a. Aliases) in C# lets developers use the alias name instead of the complete namespace. This is very useful, since namespaces in general can become quite long, an alias becomes very handy. In the code-snippet below, Excel is an alias of the Microsoft.Office.Interop.Excel namespace, yeah the default namespace is long, but we've shorten it.
using Excel = Microsoft.Office.Interop.Excel;

...

var excelapp = new Excel.Application();
excelapp.Visible = true;

9. Object Initializers

The old way, to initialize property values from outside of the class, we would have to write either use a constructor or initialize the properties separately as shown in the first code-snippet:
Child child = new Child();
child.Age = 10;
child.Name = "Bryan";
child.StreetAddress = "Seattle, WA 98124";
The code-snippet above, can be written as:
Child child = new Child() { Age = 10, Name = "Bryan", StreetAddress = "Seattle, WA 98124" };
This language feature exists in C# 3.0 and newer versions, but is not supported in C# 1.0 and C# 2.0. In short, this provides a more elegant way to achieve the same thing, in addition, it's a useful shorthand and provides good code productivity.

10. Nullable Types

Every C# developer in the world knows how to work with value types like int, double, bool, char, and so one. They're really useful, but they have one flaw: they simply cannot be set to null, except string which can be set to null. For example, a bool variable can only hold the values true or false, however, putting the question symbol ("?") or as shown below, Nullable it is possible to assign null i.e. undefined.
Nullable<bool> status = null;
int? i = null;

11. Type Inference

C# 3.0 introduces the concept of type inference with the var keyword. The var keyword was added to supportanonymous types which is another new feature in C# 3.0. Without this keyword, we would not be able to create a variable of an anonymous type if we always needed to specify the type. The best part is that the compiler determines the type automatically.
string[] Elementaryschools = {"Adams Elementary", "Hyde Elementary School", 
                              "Brookland Elementary", "Meyer Elementary School", 
                              "Thomas Elementary School", "Young Elementary School"};
var school = from name in Elementaryschools
             where name[0] == 'T'
             select name;
foreach (string n in school)
    Console.WriteLine(n);
The output in the console application will be:
Thomas Elementary School
The main reason "Thomas Elementary School" is printed out, is because we say: where name[0] == 'T', we select only the name if it begins with a 'T'. I just wanted to give some code explanation, in case it becomes complicated. The following two declarations of i are functionally equivalent:
int i = 25; //Explicitly typed
var i = 25; //Implicitly typed

12. Lambda Expressions

Lambda expressions were introduced in C# 3.0, and they use the lambda operator =>. Lambda expressions provide a more concise, functional syntax for writing anonymous methods (note: anonymous methods were introduced in C# 2.0). Since functional programming requires a more declarative style of writing code, lambda expressions are handy, in short, lambda expressions are simply functions/methods.
The following code-snippet shows the definition of a delegate and a method that can be used to initialize the delegate:
public delegate int DoubleInteger(int x);

...

class DelegateSample {
    static public int DoubleNow(int x) { return x * 2; }
}
Create and initialize an instance of the delegate, and then call it:
DoubleInteger dint = new DoubleInteger(DelegateSample.DoubleNow); 
Console.WriteLine("{0}", dint(16));
Using lambda expressions, the syntax gets even terser:
DoubleInteger dint = x => x * 2; 
Console.WriteLine("{0}", dint(16));
Lambda expressions provide a powerful shorthand that can be used to significantly speed up C# development. In short, lambda expressions allow C# developers to shorten their code significantly and make it more compact form, isn't this good huh? Of course it is good especially if we want to achieve productivity.

13. Optional and Named Parameters in C# 4.0

C# 4.0 introduces optional and named parameters. Named parameters free us from the need to remember or to look up the order of parameters in the parameter lists of invoked methods. Optional parameters enable us to omit arguments for some parameters. These two language features can be used with Microsoft Office Automation APIs—this is what the second code-snippet demonstrates below.
Word.Application wordapp = new Word.Application() { Visible = true };
object MissingValue = System.Reflection.Missing.Value;
object Filename = @"C:\sampledocument.docx"; 
object ReadOnly = true; 

wordapp.Documents.Open(ref Filename, ref MissingValue, ref ReadOnly, ref MissingValue, 
    ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,ref MissingValue, 
    ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, 
    ref MissingValue, ref MissingValue); 
With the support of optional and named parameters this becomes even shorter:
Word.Application wordapp = new Word.Application() { Visible = true };
wordapp.Documents.Open(@"C:\sampledocument.docx", ReadOnly: true);
The Microsoft.Office.Interop.Word has a method, Documents.Open this method has one required parameter, and 15 optional paramters, that's a lot huh? Thanks to named paramters we're able to omit a few or all the optional paramters by using their names and passing the argument value for each—as already demonstrated in the second code-snippet above, ReadOnly: true.

14. Asynchronous Programming with Async and Await in C# 5.0

Finally, as a bonus I've decided to demonstrate the usage of async and await in C# 5.0. Asynchronous and Synchronous programming has always been useful, especially when we want our application to be able to perform multiple operations at the same time i.e. multitasking. However, the traditional way of writing asynchronous applications is usually complicated, resulting in applications that become difficult to—write, debug, and maintain.
14.1 The traditional way
public delegate int GetValueAsync(int callDuration);

class ProgramA
{
    public ProgramA() { }

    public int GetValueMethod(int callDuration)
    {
        Thread.Sleep(callDuration); 
        int i = ReturnRandomNumber();
        return i; 
    }

    private int ReturnRandomNumber()
    {
        return new Random().Next(1, 1000);
    }
}
C# 5.0 introduces two new keywords, async and await—these help C# developers build asynchronous applications that are capable of achieving multitasking without performance issues.
14.2 The New Modern way
class ProgramB
{
    public ProgramB() { }

    public async void PrintAsync()
    {
        int a = await GetValueAsync(); 
        Console.WriteLine("The Multiplication of one" + 
            " random number with itself is: {0}", a * a);
    }

    private async Task<int> GetValueAsync()
    { 
        int i = ReturnRandomNumber();
        return await Task.FromResult<int>(i); 
    }

    private int ReturnRandomNumber()
    {
        return new Random().Next(1, 1000);
    }
}
Create and initialize one instance of each, and then invoke their methods:
static void Main(string[] args)
{
    ProgramA prgm = new ProgramA();
    GetValueAsync gasync = new GetValueAsync(prgm.GetValueMethod);
    IAsyncResult result = gasync.BeginInvoke(2000, null, null); 
            
    Console.WriteLine("Test method GetValueAsync() from ProgramA begins.");
    Thread.Sleep(300);
    int a = gasync.EndInvoke(result); 
    Console.WriteLine("The Multiplication of one random numbers is: {0}", a * a);
    Console.WriteLine("\n\n");

    ProgramB prgmB = new ProgramB();
    Console.WriteLine("Test method PrintAsync() from ProgramB begins.\n");
    prgmB.PrintAsync();

    Console.WriteLine("\n");
    Console.ReadKey(); 
}
In conclusion, we can easily avoid performance bottlenecks and enhance the overall responsiveness of our C# applications by using asynchronous programming. The new Visual Studio 2012 and .NET Framework 4.5 leverages asynchronous support via a simplified approach, async programming. In Windows 8 the support for asynchronous programming is much more extended thanks to the Windows Runtime (WinRT).

More to Explore

That's a few tips, and I hope you found them helpful. We've now just briefly had a look on 14 different approaches that help C# developers achieve code efficiency, write more compact code, and achieve productivity. However, there is more to explore—for example, in terms code efficiency, using fewer loops to achieve the same result—this is something I did not cover in this article. We'll tackle that next month. In the meantime, explore other methods and approaches that allow you to become a better C# developer, and be sure to drop me an e-mail with suggestions for future articles.
 
Happy coding!