C# Intermediate

Exploring namespaces, classes, objects, properties, indexers, exception handling, and file I/O in C#

C# Intermediate Interview with follow-up questions

Interview Question Index

Question 1: Can you explain what namespaces are in C#?

Answer:

In C#, namespaces are used to organize and group related classes, interfaces, structs, enums, and delegates. They provide a way to avoid naming conflicts and make it easier to manage and maintain code. Namespaces can be nested within other namespaces, forming a hierarchical structure.

Back to Top ↑

Follow up 1: How do you use namespaces in your code?

Answer:

To use a namespace in your code, you need to include a 'using' directive at the top of your file. This allows you to reference types from that namespace without having to fully qualify their names. For example, if you have a namespace called 'MyNamespace' and it contains a class called 'MyClass', you can use 'using MyNamespace;' at the top of your file and then simply refer to 'MyClass' in your code.

Back to Top ↑

Follow up 2: What is the 'using' directive in C#?

Answer:

The 'using' directive in C# is used to create a shortcut for referencing types from a particular namespace. It eliminates the need to fully qualify the names of types from that namespace. The 'using' directive is typically placed at the top of a file and can be used for multiple namespaces. For example, 'using System;' allows you to reference types from the 'System' namespace without having to write 'System' before each type.

Back to Top ↑

Follow up 3: Can you give an example of defining a namespace?

Answer:

Sure! Here's an example of defining a namespace in C#:

namespace MyNamespace
{
    class MyClass
    {
        // Class implementation
    }
}

In this example, we define a namespace called 'MyNamespace' and within it, we define a class called 'MyClass'. The namespace and class can have any valid names you choose.

Back to Top ↑

Follow up 4: What is the purpose of the 'global' namespace?

Answer:

The 'global' namespace in C# is the root namespace for all other namespaces. It is used to provide a global scope for types that are not explicitly declared within a namespace. Types defined in the 'global' namespace can be accessed from any other namespace without the need for a 'using' directive. However, it is generally recommended to define types within specific namespaces to avoid naming conflicts and improve code organization.

Back to Top ↑

Question 2: What are classes and objects in C#?

Answer:

In C#, a class is a blueprint or a template for creating objects. It defines the properties, methods, and events that an object of that class will have. An object, on the other hand, is an instance of a class. It is created from the class blueprint and can have its own unique values for the properties defined in the class.

Back to Top ↑

Follow up 1: How do you define a class in C#?

Answer:

To define a class in C#, you use the class keyword followed by the class name. Here's an example:

public class MyClass
{
    // class members
}
Back to Top ↑

Follow up 2: How do you create an object in C#?

Answer:

To create an object in C#, you use the new keyword followed by the class name and parentheses. Here's an example:

MyClass myObject = new MyClass();
Back to Top ↑

Follow up 3: Can you give an example of a class with properties and methods?

Answer:

Sure! Here's an example of a class called Person with properties and methods:

public class Person
{
    // properties
    public string Name { get; set; }
    public int Age { get; set; }

    // methods
    public void SayHello()
    {
        Console.WriteLine("Hello!");
    }
}
Back to Top ↑

Follow up 4: What is the difference between a class and an object?

Answer:

In C#, a class is a blueprint or a template for creating objects. It defines the properties, methods, and events that an object of that class will have. An object, on the other hand, is an instance of a class. It is created from the class blueprint and can have its own unique values for the properties defined in the class.

Back to Top ↑

Question 3: Can you explain exception handling in C#?

Answer:

Exception handling is a mechanism in C# that allows you to handle runtime errors or exceptions in a controlled manner. It helps in preventing the application from crashing and provides a way to gracefully handle errors. Exception handling involves the use of try, catch, and finally blocks. The code that may throw an exception is placed inside the try block. If an exception occurs, it is caught by the catch block, where you can handle the exception or perform any necessary actions. The finally block is optional and is used to execute code that should always be executed, regardless of whether an exception occurred or not.

Back to Top ↑

Follow up 1: What are the key keywords used in exception handling?

Answer:

The key keywords used in exception handling in C# are:

  • try: The try block is used to enclose the code that may throw an exception.
  • catch: The catch block is used to catch and handle the exception. It specifies the type of exception to catch.
  • finally: The finally block is used to specify code that should always be executed, regardless of whether an exception occurred or not.
  • throw: The throw keyword is used to manually throw an exception.
  • throw ex: The throw ex statement rethrows the exception, preserving the original stack trace.
Back to Top ↑

Follow up 2: What is the difference between 'throw' and 'throw ex' in exception handling?

Answer:

In exception handling, 'throw' and 'throw ex' are used to manually throw an exception. The main difference between them is that 'throw' preserves the original stack trace, while 'throw ex' resets the stack trace.

When you use 'throw' to rethrow an exception, the original stack trace is preserved. This means that when the exception is caught and the stack trace is examined, it will show the original location where the exception was thrown.

On the other hand, when you use 'throw ex' to rethrow an exception, the stack trace is reset. This means that when the exception is caught and the stack trace is examined, it will show the location where the exception was rethrown, rather than the original location.

Back to Top ↑

Follow up 3: Can you give an example of a try-catch-finally block?

Answer:

Sure! Here's an example of a try-catch-finally block in C#:

try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Handle the exception
}
finally
{
    // Code that should always be executed
}

In this example, the code that may throw an exception is placed inside the try block. If an exception occurs, it is caught by the catch block, where you can handle the exception. The finally block is used to specify code that should always be executed, regardless of whether an exception occurred or not.

Back to Top ↑

Follow up 4: What is the use of the 'finally' block in exception handling?

Answer:

The 'finally' block in exception handling is used to specify code that should always be executed, regardless of whether an exception occurred or not. It is optional and can be used in conjunction with the try and catch blocks.

The 'finally' block is commonly used to release resources that were acquired in the try block, such as closing files or database connections. It ensures that the cleanup code is executed even if an exception occurs.

Here's an example:

try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Handle the exception
}
finally
{
    // Code that should always be executed, e.g. releasing resources
}
Back to Top ↑

Question 4: What are properties and indexers in C#?

Answer:

Properties and indexers are mechanisms in C# that allow you to encapsulate and access the state of an object. They provide a way to define the behavior of getting and setting values for a particular data member of a class.

Back to Top ↑

Follow up 1: How do you define a property in C#?

Answer:

In C#, you can define a property using the get and set accessors. The get accessor is used to retrieve the value of the property, and the set accessor is used to assign a new value to the property. Here's an example:

public string Name
{
    get { return _name; }
    set { _name = value; }
}

In this example, the Name property has a get accessor that returns the value of the private field _name, and a set accessor that assigns a new value to _name.

Back to Top ↑

Follow up 2: What is the difference between a property and a variable?

Answer:

A property and a variable are both used to store and access data, but there are some differences between them:

  • A variable is a storage location that holds a value, while a property is a combination of a field and methods that provide access to that field.
  • A variable can be accessed directly, while a property provides a way to control the access to the underlying data.
  • A property can have additional logic in its accessors, such as validation or calculation, while a variable does not.

In summary, properties provide a more controlled and flexible way to access and manipulate data compared to variables.

Back to Top ↑

Follow up 3: Can you give an example of an indexer?

Answer:

Sure! An indexer allows you to access elements of a collection or class using an index. Here's an example of an indexer in C#:

public class MyCollection
{
    private string[] _data = new string[10];

    public string this[int index]
    {
        get { return _data[index]; }
        set { _data[index] = value; }
    }
}

In this example, the MyCollection class has an indexer that allows you to get or set elements of the private _data array using an index. For example, you can access the element at index 0 using myCollection[0].

Back to Top ↑

Follow up 4: What is the use of indexers in C#?

Answer:

Indexers are useful when you want to provide a way to access elements of a collection or class using an index, similar to how you access elements of an array. They allow you to define custom logic for getting and setting values based on the index. Indexers are commonly used in classes that represent collections, such as lists or dictionaries, to provide a more convenient and intuitive way to access the elements. They also allow you to encapsulate the internal data structure of the collection and provide a consistent interface for accessing the elements.

Back to Top ↑

Question 5: Can you explain file I/O operations in C#?

Answer:

File I/O (Input/Output) operations in C# are used to read data from and write data to files. These operations allow you to interact with files on the file system, such as reading text from a file, writing text to a file, or copying files.

C# provides several classes and methods for performing file I/O operations, such as the File class and the StreamReader and StreamWriter classes.

Back to Top ↑

Follow up 1: What namespaces are used for file I/O operations?

Answer:

The System.IO namespace is used for file I/O operations in C#. This namespace contains classes and methods for working with files, directories, and streams.

Back to Top ↑

Follow up 2: How do you read from a file in C#?

Answer:

To read from a file in C#, you can use the StreamReader class from the System.IO namespace. Here's an example:

string filePath = "path/to/file.txt";

using (StreamReader reader = new StreamReader(filePath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
Back to Top ↑

Follow up 3: How do you write to a file in C#?

Answer:

To write to a file in C#, you can use the StreamWriter class from the System.IO namespace. Here's an example:

string filePath = "path/to/file.txt";

using (StreamWriter writer = new StreamWriter(filePath))
{
    writer.WriteLine("Hello, World!");
}
Back to Top ↑

Follow up 4: Can you give an example of file I/O operations?

Answer:

Sure! Here's an example that demonstrates both reading from a file and writing to a file:

string sourceFilePath = "path/to/source.txt";
string destinationFilePath = "path/to/destination.txt";

using (StreamReader reader = new StreamReader(sourceFilePath))
using (StreamWriter writer = new StreamWriter(destinationFilePath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        writer.WriteLine(line);
    }
}
Back to Top ↑