Set - 2

Question 11 :

Will finally block get executed if the exception had not occurred?

Answer :

Yes.


Question 12 :

What is the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? Does C# support try-catch-finally blocks?

Answer :

Yes. Try-catch-finally blocks are supported by the C# compiler. 
Here's an example of a try-catch-finally block:

using System; 

public class TryTest {
	static void Main() {
		try {
			Console.WriteLine("In Try block");
			throw new ArgumentException();
		}
		catch(ArgumentException n1) {
			Console.WriteLine("Catch Block");
		}
		finally{
			Console.WriteLine("Finally Block");
		}
	}
}

Output: In Try Block
Catch Block
Finally Block

If I return out of a try/finally in C#, does the code in the finally-clause run? Yes. The code in the finally always runs. If you return out of the try block, or even if you do a "goto" out of the try, the finally block always runs, as shown in the following 
example:

using System;
class main {
	public static void Main() {
		try{
			Console.WriteLine("In Try block");
			return;
		}
		finally {
			Console.WriteLine("In Finally block");
		}
	}
}

Both "In Try block" and "In Finally block" will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it's a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there's an extra store/load of the value of the expression (since it has to be computed within the try block).


Question 13 :

Is there regular expression (regex) support available to C# developers?

Answer :

Yes. The .NET class libraries provide support for regular expressions. Look at the documentation for the System.Text.RegularExpressions namespace.


Question 14 :

Is there a way to force garbage collection?

Answer :

Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn't seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().


Question 15 :

Does C# support properties of array types?

Answer :

Yes. Here's a simple example:

using System;
class Class1{
	private string[] MyField;
	public string[] MyProperty{
		get { return MyField; }
		set { MyField = value; }
	}
}
class MainClass{
	public static int Main(string[] args){
		Class1 c = new Class1();
		string[] arr = new string[] {"apple", "banana"};
		c.MyProperty = arr;
		Console.WriteLine(c.MyProperty[0]); // "apple"
		return 0;
	}
}