Set - 7

Question 11 :

How can I get around scope problems in a try/catch?

Answer :

If you try to instantiate the class inside the try, it'll be out of scope when you try to access it from the catch block. A way to get around this is to do the following:

Connection conn = null;
try{
	conn = new Connection();
	conn.Open();
}
finally{
	if (conn != null) conn.Close();
}

By setting it to null before the try block, you avoid getting the CS0165 error (Use of possibly unassigned local variable 'conn').


Question 12 :

Why do I get an error (CS1006) when trying to declare a method without specifying a return type? 

Answer :

If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)


Question 13 :

How do I convert a string to an int in C#?

Answer :

Here's an example: 

using System;
class StringToInt{
	public static void Main(){
		String s = "105";
		int x = Convert.ToInt32(s);
		Console.WriteLine(x);
	}
}

 


Question 14 :

How do you directly call a native function exported from a DLL?

Answer :

Here's a quick example of the DllImport attribute in action:

using System.Runtime.InteropServices;
class C{
	[DllImport("user32.dll")]
	public static extern int MessageBoxA(int h, string m, string c, int type);
	public static int Main(){
		return MessageBoxA(0, "Hello World!", "Caption", 0);
	}
}

This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.


Question 15 :

What is the .NET datatype that allows the retrieval of data by a unique key?

Answer :

HashTable.