C# Interview Questions - Part Two

For Part 1 of C# Interview Questions, please refer to the below link.

Let’s look at some more questions.

  1. Which attribute of the client-side document object do we use to get a reference to the root node of the DOM tree?

rootElement

  1. What is the output of the below code?

  1. try {  
  2.     try {  
  3.         int i = 1;  
  4.         Console.WriteLine(i / 0);  
  5.     } catch (Exception e) {  
  6.         Console.WriteLine(e.GetType() + " : First Exception");  
  7.         throw;  
  8.     }  
  9. catch (DivideByZeroException e) {  
  10.     Console.WriteLine(e.GetType() + " : Second Exception");  
  11.     Console.ReadLine();  

Output

System.DivideByZeroException : First Exception
System.DivideByZeroException : Second Exception

  1. What is the difference between throw and throw ex?

    Throw will rethrow the original exception, whereas throw ex will create a new exception which, in turn, changes the stack trace.
  1. Which catch block will get caught?
    1. try {  
    2.     try {  
    3.         int i = 1;  
    4.         Console.WriteLine(i / 0);  
    5.     } catch (InvalidCastException e) {  
    6.         Console.WriteLine(e.GetType() + " : First Exception");  
    7.         throw;  
    8.     }  
    9. catch (NullReferenceException e) {  
    10.     Console.WriteLine(e.GetType() + " : Second Exception");  
    11.     Console.ReadLine();  
    12. }  
    None of the catch block will get caught. We will get an error at Console.WriteLine(i/0);

  1. What are custom/user defined exceptions?

As the name hints, the exceptions which are defined by users are termed as user-defined exceptions.

Sample Code

  1. static void Main(string[] args) {  
  2.     FileClass file = new FileClass();  
  3.     try {  
  4.         file.openFile();  
  5.     } catch (FileNotFoundException e) {  
  6.         Console.WriteLine("File not found: {0}", e.Message);  
  7.     }  
  8.     Console.ReadKey();  
  9. }  
  10. public class FileNotFoundException: Exception {  
  11.     public FileNotFoundException(string message): base(message) {}  
  12. }  
  13. public class FileClass {  
  14.     string filepath = "D:\\temp\\123.txt";  
  15.     public void openFile() {  
  16.         if (!File.Exists(filepath)) {  
  17.             throw (new FileNotFoundException("No File Exists"));  
  18.         } else {  
  19.             Console.WriteLine("File not Found: {0}", filepath);  
  20.         }  
  21.     }  
  22. }  

Output

File not found: No File Exists.

  1. What are Tracers?

    Tracer is a class used to produce the messages that monitor the code execution.
  1. What is Tuple?

Tuple is a data structure that represents a single set of data.

Sample

  1. var member = new Tuple<string, string, int>("Sridhar""Sharma", 2006);  
  2. Console.WriteLine(member.Item1+" "+ member.Item2 +" is a member of csharpcorner since "+ member.Item3);  
  3. Console.ReadLine();  

Output

Sridhar Sharma is a member of csharpcorner since 2006

  1. What are Resource Files? Or, How will you generate Messages in languages other than English?

A Resource file is an XML file that can contain strings and other resources, such as image file paths. Resource files are typically used to store user interface strings like custom messages that must be translated into other languages.

Let us have an example to demonstrate use of Resources.

  • Add a Resource file by right clicking on project and name it as CustomMessages.

    C#

  • Add some sample values in it.

    C#

  • Add another Resource file and rename it as hi-IN.

    Note

    hi-IN stands for hindi language from India (http://www.localeplanet.com/dotnet/hi-IN/index.html)

    C#

      • Let’s add some data to it.

        C#

      • Add a Windows form and place two buttons. One button click will display a message in English and the other one will display the message in Hindi.
        1. private void button1_Click(object sender, EventArgs e) {  
        2.     Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");  
        3.     MessageBox.Show(CustomMessages.HelloWorld);  
        4. }  
        5. private void button2_Click(object sender, EventArgs e) {  
        6.     Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("hi-IN");  
        7.     MessageBox.Show(CustomMessages.HelloWorld);  
        8. }  

Let us run the code and see how the messages would be displayed.

C#

Let us click "Hindi".

C#

That’s it.

  1. How to retrieve 3rd highest salaried employee from a list of employees?
    1. var employee = employees  
    2. .OrderByDescending(e => e.Salary)  
    3. .Skip(2).First();  

  1. What is an Array?

    An array is a collection of items of the same data type.
    1. int[] rollnumbers = new int[] { 1291, 1292, 1293, 1294 };  

  1. What is the difference between Parse and TryParse?

Parsing is the process of converting a value from one data type to another.

The Prase() method throws three different types of exceptions depending upon the data provided - if the input is null, or in other format, or out of range.

    1. If the parameter value is null, then it will throw ArgumentNullException.
    2. If the parameter value is other than specified data type, it will throw FormatException.
    3. If the parameter value is out of range, then it will throw OverflowException.

  1. string number = "1234";  
  2. string n = null;  
  3. try {  
  4.     Console.WriteLine(int.Parse(number));  
  5.     Console.WriteLine(int.Parse(n));  
  6. catch (Exception e) {  
  7.     Console.WriteLine(e);  
  8.     Console.ReadLine();  
  9.     throw;  
  10. }  

When we run the above code, we will get the below output.

1234

System.ArgumentNullException: Value cannot be null.

Parameter name: String

at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)

at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)

at System.Int32.Parse(String s)

at LambdaExpressionSample.Program.Main(String[] args) in D:\Projects\SampleInterview\LambdaExpressionSample\Program.cs:line 28

In order to come out of these runtime issues, it is better to use TryParse().

Let us modify the above code and see how it will behave.

  1. string number = "1234";  
  2. string n = null;  
  3. int num;  
  4. bool bCheck = int.TryParse(n, out num);  
  5. try {  
  6.     Console.WriteLine(int.Parse(number));  
  7.     if (bCheck) {  
  8.         Console.WriteLine(int.Parse(n));  
  9.     }  
  10.     Console.ReadLine();  
  11. catch (Exception e) {  
  12.     Console.WriteLine(e);  
  13.     Console.ReadLine();  
  14.     throw;  
  15. }  

When we run the above code, we will get the below output.

1234

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now