Set - 4

Question 6 :

What optimizations does the C# compiler perform when you use the /optimize+ compiler option?

Answer :

The following is a response from a developer on the C# compiler team:
We get rid of unused locals (i.e., locals that are never read, even if assigned).
We get rid of unreachable code.
We get rid of try-catch w/ an empty try.
We get rid of try-finally w/ an empty try (convert to normal code...).
We get rid of try-finally w/ an empty finally (convert to normal code...).
We optimize branches over branches:
gotoif A, lab1
goto lab2:
lab1:
turns into: gotoif !A, lab2
lab1:
We optimize branches to ret, branches to next instruction, and branches to branches.


Question 7 :

How can I create a process that is running a supplied native executable (e.g., cmd.exe)?

Answer :

The following code should run the executable and wait for it to exit before
continuing:

using System;
using System.Diagnostics;
public class ProcessTest {
	public static void Main(string[] args) {
		Process p = Process.Start(args[0]);
		p.WaitForExit();
		Console.WriteLine(args[0] + " exited.");
	}
}

Remember to add a reference to System.Diagnostics.dll when you compile.


Question 8 :

What is the difference between the System.Array.CopyTo() and System.Array.Clone()?

Answer :

The first one performs a deep copy of the array, the second one is shallow.


Question 9 :

How do I declare inout arguments in C#?

Answer :

The equivalent of inout in C# is ref. , as shown in the following
example:

public void MyMethod (ref String str1, out String str2){
	...
}

When calling the method, it would be called like this:

String s1;
String s2;
s1 = "Hello";
MyMethod(ref s1, out s2);
Console.WriteLine(s1);
Console.WriteLine(s2);

Notice that you need to specify ref when declaring the function and calling it.


Question 10 :

Is there a way of specifying which block or loop to break out of when working with nested loops?

Answer :

The easiest way is to use goto:

using System;
class BreakExample{
	public static void Main(String[] args){
		for(int i=0; i<3; i++){
			Console.WriteLine("Pass {0}: ", i);
			for( int j=0 ; j<100 ; j++ ){
				if ( j == 10) goto done;
					Console.WriteLine("{0} ", j);
			}
			Console.WriteLine("This will not print");
		}
		done:
		Console.WriteLine("Loops complete.");
	}
}