Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, August 15, 2012

C# developer interview questions and answers


Takeaway: Software development hiring managers and potential interviewees will find these open-ended C# proficiency interview questions and answers useful.

Good help is hard to find. There is an art to finding a developer who fits well in your organization in terms of personality and work ethic; fortunately, it’s more straightforward to determine their technical expertise.
I worked at a couple of places where development managers loved drilling job candidates on syntax while having them write code, and it was clearly a stressful experience for the interviewee. I do not like asking specific syntax questions during interviews since most developers do not know language syntax or class names off the top of their heads.
In terms of the basic interview, I prefer to ask open-ended questions where the candidate can explain concepts and how they would attack problems. Some organizations like to give candidates tests or have them eyeball code snippets to spot problems, and I think those are good evaluation tools.
This is the first installment in our series of programming language-specific development interview questions and answers. Here is a list of questions (and the answers to those questions) that will help you get a feel for a candidate’s proficiency with C#. You can ask follow-up questions based on their replies.

What are namespaces, and how they are used?

Namespaces are used to organize classes within the .NET Framework. They dictate the logical structure of the code. They are analogous to Java packages, with the key difference being Java packages define the physical layout of source files (directory structure) while .NET namespaces do not. However, many developers follow this approach and organize their C# source files in directories that correlate with namespaces. The .NET Framework has namespaces defined for its many classes, such as System.Xml–these are utilized via the using statement. Namespaces are assigned to classes via the namespace keyword.

What is a constructor?

A constructor is a class member executed when an instance of the class is created. The constructor has the same name as the class, and it can be overloaded via different signatures. Constructors are used for initialization chores.

What is the GAC, and where is it located?

The GAC is the Global Assembly Cache. Shared assemblies reside in the GAC; this allows applications to share assemblies instead of having the assembly distributed with each application. Versioning allows multiple assembly versions to exist in the GAC–applications can specify version numbers in the config file. The gacutil command line tool is used to manage the GAC.

Why are strings in C# immutable?

Immutable means string values cannot be changed once they have been created. Any modification to a string value results in a completely new string instance, thus an inefficient use of memory and extraneous garbage collection. The mutable System.Text.StringBuilder class should be used when string values will change.

What is DLL Hell, and how does .NET solve it?

DLL Hell describes the difficulty in managing DLLs on a system; this includes multiple copies of a DLL, different versions, and so forth. When a DLL (or assembly) is loaded in .NET, it is loaded by name, version, and certificate. The assembly contains all of this information via its metadata. The GAC provides the solution, as you can have multiple versions of a DLL side-by-side.

How are methods overloaded?

Methods are overloaded via different signatures (number of parameters and types). Thus, you can overload a method by having different data types, different number of parameters, or a different order of parameters.

How do you prevent a class from being inherited?

The sealed keyword prohibits a class from being inherited.

What is the execution entry point for a C# console application?

The Main method.

How do you initiate a string without escaping each backslash?

You put an @ sign in front of the double-quoted string.
String ex = @"This has a carriage return\r\n"

What is the difference between a struct and a class?

Structs cannot be inherited. Structs are passed by value and not by reference. Structs are stored on the stack not the heap. The result is better performance with Structs.

What is a singleton?

A singleton is a design pattern used when only one instance of an object is created and shared; that is, it only allows one instance of itself to be created. Any attempt to create another instance simply returns a reference to the first one. Singleton classes are created by defining all class constructors as private. In addition, a private static member is created as the same type of the class, along with a public static member that returns an instance of the class. Here is a basic example:
public class SingletonExample {
private static SingletonExample _Instance;
private SingletonExample () { }
public static SingletonExample GetInstance() {
if (_Instance == null)  {
_Instance = new SingletonExample ();
}
return _Instance;
}
}

What is boxing?

Boxing is the process of explicitly converting a value type into a corresponding reference type. Basically, this involves creating a new object on the heap and placing the value there. Reversing the process is just as easy with unboxing, which converts the value in an object reference on the heap into a corresponding value type on the stack. The unboxing process begins by verifying that the recipient value type is equivalent to the boxed type. If the operation is permitted, the value is copied to the stack.

Thursday, August 11, 2011

Passing Arrays Using ref and out


Like all out parameters, an out parameter of an array type must be assigned before it is used; that is, it must be assigned by the callee. For example:
public static void MyMethod(out int[] arr) 
{
   arr = new int[10];   // definite assignment of arr
}
Like all ref parameters, a ref parameter of an array type must be definitely assigned by the caller. Therefore, there is no need to be definitely assigned by the callee. A ref parameter of an array type may be altered as a result of the call. For example, the array can be assigned the null value or can be initialized to a different array. For example:
public static void MyMethod(ref int[] arr) 
{
   arr = new int[10];   // arr initialized to a different array
}
The following two examples demonstrate the difference between out and ref when used in passing arrays to methods.

Example 1

In this example, the array myArray is declared in the caller (the Main method), and initialized in the FillArray method. Then, the array elements are returned to the caller and displayed.
// cs_array_ref_and_out.cs
using System; 
class TestOut 
{
   static public void FillArray(out int[] myArray) 
   {
      // Initialize the array:
      myArray = new int[5] {1, 2, 3, 4, 5};
   }

   static public void Main() 
   {
      int[] myArray; // Initialization is not required

      // Pass the array to the callee using out:
      FillArray(out myArray);

      // Display the array elements:
      Console.WriteLine("Array elements are:");
      for (int i=0; i < myArray.Length; i++)
         Console.WriteLine(myArray[i]);
   }
}

Output

Array elements are:
1
2
3
4
5

Example 2

In this example, the array myArray is initialized in the caller (the Main method), and passed to the FillArray method by using the ref parameter. Some of the array elements are updated in the FillArray method. Then, the array elements are returned to the caller and displayed.
// cs_array_ref_and_out2.cs
using System; 
class TestRef 
{
   public static void FillArray(ref int[] arr) 
   {
      // Create the array on demand:
      if (arr == null)
         arr = new int[10];
      // Otherwise fill the array:
      arr[0] = 123;
      arr[4] = 1024;
   }

   static public void Main () 
   {
      // Initialize the array:
      int[] myArray = {1,2,3,4,5};  

      // Pass the array using ref:
      FillArray(ref myArray);

      // Display the updated array:
      Console.WriteLine("Array elements are:");
      for (int i = 0; i < myArray.Length; i++) 
         Console.WriteLine(myArray[i]);
   }
}

Output

Array elements are:
123
2
3
4
1024

C# Array - Jagged Array


A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array-of-arrays." This topic contains examples of declaring, initializing, and accessing jagged arrays.
The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:
int[][] myJaggedArray = new int[3][];
Before you can use myJaggedArray, its elements must be initialized. You can initialize the elements like this example:
myJaggedArray[0] = new int[5];
myJaggedArray[1] = new int[4];
myJaggedArray[2] = new int[2];
Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers.
It is also possible to use initializers to fill the array elements with values, in which case you don't need the array size, for example:
myJaggedArray[0] = new int[] {1,3,5,7,9};
myJaggedArray[1] = new int[] {0,2,4,6};
myJaggedArray[2] = new int[] {11,22};
You can also initialize the array upon declaration like this:
int[][] myJaggedArray = new int [][] 
                        {
                           new int[] {1,3,5,7,9},
                           new int[] {0,2,4,6},
                           new int[] {11,22}
                        };
You can use the following shortcut (notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements):
int[][] myJaggedArray = {
                           new int[] {1,3,5,7,9},
                           new int[] {0,2,4,6},
                           new int[] {11,22}
                        };
You can access individual array elements like these examples:
// Assign 33 to the second element of the first array:
myJaggedArray[0][1] = 33;
// Assign 44 to the second element of the third array:
myJaggedArray[2][1] = 44;
It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains two-dimensional array elements of different sizes:
int[][,] myJaggedArray = new int [3][,] 
                         {
                            new int[,] { {1,3}, {5,7} },
                            new int[,] { {0,2}, {4,6}, {8,10} },
                            new int[,] { {11,22}, {99,88}, {0,9} } 
                         };
You can access individual elements like this example, which displays the value of the element [1,0] of the first array (value 5):
Console.Write("{0}", myJaggedArray[0][1,0]);

Example

This example builds an array, myArray, whose elements are arrays. Each one of the array elements has a different size.
// cs_array_of_arrays.cs
using System;
public class ArrayTest 
{
   public static void Main() 
   {
      // Declare the array of two elements:
      int[][] myArray = new int[2][];

      // Initialize the elements:
      myArray[0] = new int[5] {1,3,5,7,9};
      myArray[1] = new int[4] {2,4,6,8};

      // Display the array elements:
      for (int i=0; i < myArray.Length; i++) 
      {
         Console.Write("Element({0}): ", i);

         for (int j = 0 ; j < myArray[i].Length ; j++)
            Console.Write("{0}{1}", myArray[i][j],
                          j == (myArray[i].Length-1) ? "" : " ");

         Console.WriteLine();
      }
   }
}

Output

Element(0): 1 3 5 7 9
Element(1): 2 4 6 

C# Array - Multi Dimensional


Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns:

int[,] myArray = new int[4,2];
Also, the following declaration creates an array of three dimensions, 4, 2, and 3:

int[,,] myArray = new int [4,2,3];

Array Initialization

You can initialize the array upon declaration as shown in the following example:

int[,] myArray = new  int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
You can also initialize the array without specifying the rank:

int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};
If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:

int[,] myArray;
myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};   // OK
myArray = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error
You can also assign a value to an array element, for example:

myArray[2,1] = 25;

Passing Arrays as Parameters

You can pass an initialized array to a method. For example:

PrintArray(myArray);
You can also initialize and pass a new array in one step. For example:

PrintArray(new int[,] {{1,2}, {3,4}, {5,6}, {7,8}});

Example

In this example, a two-dimensional array is initialized and passed to the PrintArray method, where its elements are displayed.

// cs_td_arrays.cs
using System;
public class ArrayClass 
{
   static void PrintArray(int[,] w) 
   {
      // Display the array elements:
      for (int i=0; i < 4; i++) 
         for (int j=0; j < 2; j++)
            Console.WriteLine("Element({0},{1})={2}", i, j, w[i,j]);
   }

   public static void Main() 
   {
      // Pass the array as a parameter:
      PrintArray(new int[,] {{1,2}, {3,4}, {5,6}, {7,8}});
   }
}

Output


Element(0,0)=1
Element(0,1)=2
Element(1,0)=3
Element(1,1)=4
Element(2,0)=5
Element(2,1)=6
Element(3,0)=7
Element(3,1)=8

.Net Array - single Dimensional


You can declare an array of five integers as in the following example:

int[] myArray = new int [5];
This array contains the elements from myArray[0] to myArray[4]. The new operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to zero.
An array that stores string elements can be declared in the same way. For example:

string[] myStringArray = new string[6];

Array Initialization

It is possible to initialize an array upon declaration, in which case, the rank specifier is not needed because it is already supplied by the number of elements in the initialization list. For example:

int[] myArray = new int[] {1, 3, 5, 7, 9};
A string array can be initialized in the same way. The following is a declaration of a string array where each array element is initialized by a name of a day:

string[] weekDays = new string[]
               {"Sun","Sat","Mon","Tue","Wed","Thu","Fri"};
When you initialize an array upon declaration, it is possible to use the following shortcuts:

int[] myArray = {1, 3, 5, 7, 9};
string[] weekDays = {"Sun","Sat","Mon","Tue","Wed","Thu","Fri"};
It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable. For example:

int[] myArray;
myArray = new int[] {1, 3, 5, 7, 9};   // OK
myArray = {1, 3, 5, 7, 9};   // Error

Value Type and Reference Type Arrays

Consider the following array declaration:

MyType[] myArray = new MyType[10];
The result of this statement depends on whether MyType is a value type or a reference type. If it is a value type, the statement results in creating an array of 10 instances of the type MyType. If MyType is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference.
For more information on value types and reference types, see Types.

Passing Arrays as Parameters

You can pass an initialized array to a method. For example:

PrintArray(myArray);
You can also initialize and pass a new array in one step. For example:

PrintArray(new int[] {1, 3, 5, 7, 9});

Example

In the following example, a string array is initialized and passed as a parameter to the PrintArray method, where its elements are displayed:

// cs_sd_arrays.cs
using System;
public class ArrayClass 
{
   static void PrintArray(string[] w) 
   {
      for (int i = 0 ; i < w.Length ; i++) 
         Console.Write(w[i] + "{0}", i < w.Length - 1 ? " " : "");
      Console.WriteLine();
   }

   public static void Main() 
   {
      // Declare and initialize an array:
      string[] WeekDays = new string []
         {"Sun","Sat","Mon","Tue","Wed","Thu","Fri"};

      // Pass the array as a parameter:
      PrintArray(WeekDays);
   }
}

Output


Sun Sat Mon Tue Wed Thu Fri

List SQL Server databases


Method 1
using System.Data;
using System.Data.SqlClient;
...
// Substitute your connection string below in conxString 
String conxString = 
   "Data Source=MYSERVER; Integrated Security=True;";
 
using (SqlConnection sqlConx = new SqlConnection (conxString))
   {
   sqlConx.Open();
   DataTable tblDatabases = sqlConx.GetSchema ("Databases");
   sqlConx.Close();
 
   foreach (DataRow row in tblDatabases.Rows)
   {
      Console.WriteLine ("Database: " + row["database_name"]);
   }


Method 2 


System.Data.SqlClient.SqlConnection SqlCon = newSystem.Data.SqlClient.SqlConnection("server=192.168.0.1;uid=sa;pwd=1234");
SqlCon.Open();

System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand();
SqlCom.Connection = SqlCon;
SqlCom.CommandType = CommandType.StoredProcedure;
SqlCom.CommandText = "sp_databases";
System.Data.SqlClient.SqlDataReader SqlDR;
SqlDR = SqlCom.ExecuteReader();
while(SqlDR.Read())
{
MessageBox.Show(SqlDR.GetString(0));
}