20 C# Interview Questions (For Freshmen) 2023

Hey C# lovers! So you've covered the basics, and now you're itching to tackle some more challenging interview questions, eh? Maybe you're a newcomer looking to impress in your first interview, or just trying to build on your C# expertise. Guess what? You have come to the right place, my friend!

In this article, we'll delve into 20 great C# interview questions for newbies; a notch above the basics but still totally doable. Among these questions, you will find a variety of questions to test your logical thinking, code analysis skills and those very important programming concepts.

Ready to surprise your interviewers?

bring it on!

What are namespaces in C#?
Answer
Namespaces in C# are a way to group related types and improve code organization. It is used to avoid naming conflicts between different classes or types that might have the same identifier. Namespaces work as a hierarchy, within which you can nest namespaces, and they can span multiple files or even libraries.

For example:

namespace Company.Project
{
    
    
    class MyClass
    {
    
    
        // Class implementation
    }
}

In this example, the class MyClass is declared within the Company.Project namespace.

What is the purpose of the "using" directive in C#?
Answer
The using directive in C# has two main purposes:

Namespace import: using allows you to import a namespace so that you can use types and members defined in that namespace without specifying their fully qualified names. It makes your code more readable and reduces code complexity. For example:

using System;

    class Program
    {
    
    
        static void Main()
        {
    
    
            // Without the 'using' directive, you would need to write: System.Console.WriteLine("Hello, World!");
            Console.WriteLine("Hello, World!");
        }
    }

Resource management: The using statement is used to help you manage resources that implement the IDisposable interface, such as file streams, network connections, or database connections. The using statement ensures that the Dispose() method is called on the resource when the code block is exited, thereby properly releasing the resource. For example:

using System.IO;

    class Program
    {
    
    
        static void Main()
        {
    
    
            using (StreamReader reader = new StreamReader("file.txt"))
            {
    
    
                // Code to read from the file
            } // At this point, the Dispose() method of the StreamReader is automatically called, releasing resources.
        }
    }

What are reference types in C#?
Answer
A reference type in C# is a type that stores a reference to a memory location that stores data, not the actual data itself. When you create objects from classes or use arrays, delegates, interfaces, or most built-in data structures in the .NET Framework, you are using reference types. Unlike value types, reference types are allocated on the heap, and their memory is managed by the garbage collector.

Key aspects of reference types:

When you pass a reference type as a method parameter or assign it to another variable, both variables refer to the same memory location. Therefore, modification of one variable will affect the other variable.
Reference types can have a null value, which means they do not refer to any memory location or object.

class Person
{
    
    
    public string Name {
    
     get; set; }
}

Person person1 = new Person {
    
     Name = "John" };
Person person2 = person1; // Both person1 and person2 reference the same object in memory
person2.Name = "Jane"; // Changing person2.Name also updates person1.Name, as they both refer to the same object

How to declare methods in C#?
Answer
A method in C# is a block of code that performs a specific task and can be called as many times as necessary. To declare a method, you specify its access level, return type, method name, and parameter list (if applicable) in the class. Here is an example:

public class Calculator
{
    
    
    public int Add(int a, int b)
    {
    
    
        int sum = a + b;
        return sum;
    }
}

Add In this example, we declare a method named with the public access modifier, an int return type, and two parameters of type int. This method calculates the sum of two numbers and returns the result.

What are the basic access modifiers available in C#?
Answer
Access modifiers in C# control the visibility and accessibility of class members (methods, properties, fields, etc.) and the class itself. The basic access modifiers available in C# are:

public: Members and classes with the access modifier public can be accessed from any code in the same assembly or another assembly that references it.
private: Members declared as private can only be accessed within the same class. They are not visible to other classes, even within the same assembly. private By default, a class member if no access modifier is specified.
protected: Members declared with the protected access modifier can be accessed in the same class as well as in derived classes. They are not visible to other non-derived classes in the same assembly.
Internal: Members and classes with the internal access modifier can be accessed anywhere in the same assembly, but are not visible to other assemblies.
protected inside: Members declared with the protected internal access modifier can be accessed in the same assembly or by derived classes in another assembly.

public class MyClass
{
    
    
    public int PublicMember;
    private int PrivateMember;
    protected int ProtectedMember;
    internal int InternalMember;
    protected internal int ProtectedInternalMember;
}

What are constructors in C#?
Answer
A constructor is a special method in a class that is called when an object of that class is created. A constructor has the same name as a class and has no explicit return type. Constructors can be overloaded, which means there can be multiple constructors in a class with different parameter lists.

The constructor is used to:

Initialize the state of the object (set default values ​​for properties, fields, etc.).
Allocate resources, such as memory or network connections.
Validate input parameters or ensure objects are in a consistent state.
example:

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

    // Default constructor
    public Person()
    {
    
    
        Name = "Unknown";
        Age = 0;
    }

    // Parameterized constructor
    public Person(string name, int age)
    {
    
    
        Name = name;
        Age = age;
    }
}

// Usage:
Person person1 = new Person(); // Calls the default constructor
Person person2 = new Person("John", 25); // Calls the parameterized constructor

What is an indexer in C#?
Answer
An indexer in C# is a class member that allows you to access an object's elements using index notation, similar to how you access elements in an array or collection. Indexers provide a more intuitive way to interact with elements stored in a class, especially if it contains a collection or array.

To define an indexer, you need to use the keyword this, the type of the element you want to access, and implement get and set accessors to access and modify the underlying element.

Here is an example of an indexer implementation for a simple custom collection class:

public class MyCollection
{
    
    
    private int[] items = new int[10];

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

// Usage:
MyCollection collection = new MyCollection();
collection[0] = 42; // Uses the indexer's set accessor
int firstItem = collection[0]; // Uses the indexer's get accessor

How to create custom exception handling in C#?
Answer
To create custom exception handling in C#, you can create a custom exception class that inherits from the built-in System.Exception class or one of its derived classes. Custom exceptions are useful when the built-in exception classes do not cover specific error conditions in your application.

Here is an example of a custom exception class:

public class CustomException : Exception
{
    
    
    public CustomException() : base()
    {
    
    
    }

    public CustomException(string message) : base(message)
    {
    
    
    }

    public CustomException(string message, Exception innerException) : base(message, innerException)
    {
    
    
    }
}

CustomException now you can throw and catch in your code:

try
{
    
    
    // Some code that might throw a CustomException
    throw new CustomException("This is a custom exception");
}
catch (CustomException ex)
{
    
    
    Console.WriteLine("Caught a CustomException: " + ex.Message);
}

How to prevent class inheritance in C#?
Answer
To prevent class inheritance in C#, you can use the sealed keyword when declaring a class. A sealed class cannot be inherited by any other class, and attempting to inherit from a sealed class will result in a compile-time error.

public sealed class NonInheritableClass
{
    
    
    // Class implementation
}

// This will result in a compile-time error:
public class MyClass : NonInheritableClass
{
    
    
}

What is the difference between "const" and "readonly" in C#?
Answer
const and readonly are both used in C# to create variables that cannot be changed after assignment, but they have some differences:

const:
Can only be applied to fields, not properties.
Must be assigned a value at declaration time.
The assigned value must be a constant expression that can be resolved at compile time.
const fields are implicitly static, you cannot use instance members to initialize them.

public class Constants
{
    
    
    public const double Pi = 3.14159;
}
readonly:

Can be applied to fields and properties.
Can be assigned at declaration time or within a constructor.
The assigned value can be a constant expression or a non-constant expression that is resolved at runtime.
A readonly field can be a static member or an instance member, depending on your needs.

public class ReadOnlyFields
{
    
    
    public readonly int InstanceField;
    public static readonly int StaticField;

    public ReadOnlyFields(int instanceValue, int staticValue)
    {
    
    
        InstanceField = instanceValue;
        StaticField = staticValue;
    }
}

Summary of differences:

const is a compile-time constant whose value cannot depend on a runtime condition. readonly is a runtime constant whose value can be determined at runtime.
const fields are implicitly static, while readonly fields can be static members or instance members.
What is Garbage Collection in C#?
Answer
Garbage collection (GC) in C# is an automatic memory management system provided by the .NET Framework. It is responsible for freeing memory that is no longer used by the application. The garbage collector tracks objects allocated on the heap, determines which objects are no longer reachable, and reclaims the corresponding memory space.

The main benefits of garbage collection are:

Improves developer productivity by reducing boilerplate code for manual memory management.
Prevents memory leaks as unused memory is automatically reclaimed.
Protects against certain programming errors, such as dangling pointers or double free problems.
C#'s garbage collection is non-deterministic, which means you can't predict exactly when the garbage collector will run. It uses a generational approach where objects are divided into generations to reduce the time and resources spent on garbage collection. The garbage collector typically runs when available memory gets low or when the system is idle.

While garbage collection can provide benefits, care should still be taken when dealing with resource-intensive objects such as file handlers or database connections. Classes that handle such resource management should implement the IDisposable interface to allow deterministic release of resources.

Describes object-oriented programming (OOP) in C#. Name the main OOP concepts.
Answer
Object-oriented programming (OOP) is a programming paradigm that represents concepts as objects with properties (fields or attributes) and behavior (methods). The goal of OOP is to produce reusable, maintainable, and modular code by emphasizing separation of concerns and adhering to OOP principles.

C# is an object-oriented programming language that fully supports OOP concepts. The main OOP concepts in C# are:

Encapsulation: The process of bundling data (properties) and methods (functions) that operate on the data into a single unit (class). Encapsulation helps protect an object's internal state and controls access to its properties.
Inheritance base: The ability of a class to inherit properties, methods, and behaviors from another class to enable code reuse and represent a hierarchy of related objects. In C#, a class can only inherit from one class, but can implement multiple interfaces.
Polymorphism: Polymorphism is the ability of a single interface to represent different types or methods to have multiple implementations based on derived types. In C#, polymorphism can be achieved through overloading (using the same method name and different parameters in the same type) and overriding (redefining a base class method in a derived class).
Abstraction: Abstraction is the process of simplifying complex real-world objects and concepts by focusing on their essential characteristics. In C#, abstraction is achieved by using abstract classes and interfaces to define a set of public properties and methods that related types must implement.
How to create generic class or method in C#?
Answer
A generic class or method in C# is one that can use any type without explicit type conversion or type checking at runtime. Generic types increase code reusability, flexibility, and type safety.

To create a generic class or method in C#, you need to use angle brackets to define type parameters. Here's an example of a generic class and a generic method:

// A generic class example
public class GenericList<T>
{
    
    
    // Class implementation using the generic type parameter T
}

// A generic method example
public static T Max<T>(T value1, T value2) where T : IComparable<T>
{
    
    
    return value1.CompareTo(value2) > 0 ? value1 : value2;
}

In this example, T is the type parameter of the generic class GenericList and the generic method Max(T, T). The method also uses a constraint ( where T : IComparable ) to ensure that the type parameter T implements the IComparable interface.

What is the difference between an abstract class and an interface in C#?
Answer
Both abstract classes and interfaces in C# are used to define abstract entities, but they have some differences:

Abstract class:

It is possible to have both abstract and non-abstract (implementation) methods.
There can be fields (variables), properties and events.
Constructors and destructors are supported.
Can have access modifiers (public, protected, internal, etc.) for members.
Inheritance is supported; a class can only inherit from one abstract class.
There can be full implementations for some methods or properties, but they cannot be instantiated directly.
interface:

Can only have method, property and event signatures (no implementation).
Cannot have fields or constructors.
No member (method, property, event) can have an access modifier (all members are implicitly public).
Multiple inheritance is supported; a class can implement multiple interfaces.
There can't be any implementation details, just the member's signature.
In summary, an abstract class provides a base implementation that can be shared among multiple derived classes, while an interface defines a contract that any implementing class must abide by. Use abstract classes when you want to provide some default behavior, use interfaces when you need multiple inheritance or want to strictly define a common functional contract.

What is the difference between "out" and "ref" parameters in C#?
Answer
both ref and parameters in outC# are used to pass parameters by reference, allowing the method to modify the value of the passed variable outside the method. However, there are some differences between the two:

reference:

A variable ref passed as an argument must be initialized before being passed to the method.
The called method doesn't have to assign a value to the ref parameter because it already has a value. example:

  public void Swap(ref int a, ref int b)
  {
    
    
      int temp = a;
      a = b;
      b = temp;
  }

  int x = 1, y = 2;
  Swap(ref x, ref y); // x = 2, y = 1 after the method call

output:

The variable out passed as a parameter does not need to be initialized before being passed to the method.
The method called out must assign values ​​to the parameters before the method returns. example:

  public void Divide(int a, int b, out int quotient, out int remainder)
  {
    
    
      quotient = a / b;
      remainder = a % b;
  }

  int q, r;
  Divide(10, 3, out q, out r); // q = 3, r = 1 after the method call

In summary, use ref parameters when you want the called method to modify an already initialized variable, and use out parameters when you want the called method to provide a value that does not depend on the initial value of the passed variable.

Describes the concept of delegation in C#.
Answer
A delegate in C# is a reference type that represents a method with a specific signature. Delegates allow you to treat methods as objects and pass them as parameters, return them from methods, or store them as properties. Delegates provide a way to create function pointers or callbacks, making it possible to develop more flexible and extensible applications.

Delegates are especially useful when designing event-driven systems, where components must react to other component events or signals without tight coupling. The following is an example of delegate declaration, instantiation and invocation:

// Declare a delegate type with a specific signature
public delegate void MyDelegate(string message);

// A method that matches the delegate signature
public static void Greet(string message)
{
    
    
    Console.WriteLine("Hello, " + message);
}

// Create an instance of the delegate, assigning the method to it
MyDelegate greetDelegate = new MyDelegate(Greet);

// Invoke the delegate
greetDelegate("World");

C# also supports generic delegates, multicast delegates, and the built-in delegates Func<T, TResult> and Action delegates (introduced in .NET Framework 3.5) for increased flexibility and usability.

", "Equals" and "ReferenceEquals" methods?
Answer
In C#, "
", "Equals" and "ReferenceEquals" are used to compare objects or values ​​for equality, but there are some differences:

== operator: "" operator compares two objects or values ​​for equality. For value types, it checks for value equality. For reference types, it checks for equality of object references, meaning they point to the same object in memory. For custom reference types , can be overloaded by "" operator to override this behavior.

   int a = 10;
   int b = 10;
   Console.WriteLine(a == b); // True, because the values are equal

   string s1 = "hello";
   string s2 = new String("hello".ToCharArray());

Console.WriteLine(s1 == s2); // False, because the object references are different
Equals: The "Equals" method compares two objects for equality by checking their values ​​rather than their references. The default implementation of "Equals" for reference types checks for reference equality, but it can be overridden in custom classes to provide value-based comparisons.

   string s1 = "hello";
   string s2 = new String("hello".ToCharArray());
   Console.WriteLine(s1.Equals(s2)); // True, because the values are equal

ReferenceEquals: The "ReferenceEquals" method checks whether two object references are equal, meaning they point to the same object in memory. It doesn't compare values. This method cannot be overridden and is useful when strict reference comparisons need to be performed.

   string s1 = "hello";
   string s2 = new String("hello".ToCharArray());
   Console.WriteLine(ReferenceEquals(s1, s2)); // False, because the object references are different

In summary, use the "==" operator for simple value comparisons and reference comparisons, use "Equals" when you need to perform value-based comparisons on reference types, and use "ReferenceEquals" when you need to specifically compare object references.

Explains the concept of dependency injection in C#.
Answer
Dependency Injection (DI) is a design pattern used in C# and other object-oriented languages ​​that helps to separate the creation and management of object dependencies, thereby improving the modularity, maintainability, and testability of applications.

In the context of C#, dependency injection is a technique in which an object receives its dependencies (the objects, services, or values ​​it depends on) from an external source, rather than creating, managing, or finding those dependencies directly. Dependency injection can be implemented using constructor injection, property injection or method injection:

Constructor Injection: Dependencies are passed to an object through its constructor. This is the most common and recommended approach to dependency injection, as it enforces that the object is created with all required dependencies and is in a valid state.

   public class UserService
   {
    
    
       private readonly ILogger _logger;

       public UserService(ILogger logger)
       {
    
    
           _logger = logger;
       }

       public void DoSomething()
       {
    
    
           _logger.Log("User Service is doing something.");
       }
   }

Property Injection: Dependencies are set through public properties or setters of objects. Use this technique when dependencies are optional or can change during the object lifetime.

   public class UserService
   {
    
    
       public ILogger Logger {
    
     get; set; }

       public void DoSomething()
       {
    
    
           Logger?.Log("User Service is doing something.");
       }
   }

Method Injection: Dependencies are passed to objects through methods. This technique is suitable when an object requires only one method and not a specific dependency for the object's entire lifetime.

   public class UserService
   {
    
    
       public void DoSomething(ILogger logger)
       {
    
    
           logger.Log("User Service is doing something.");
       }
   }

In C#, popular dependency injection frameworks such as Autofac, Unity, or the built-in .NET Core dependency injection can be used to manage and resolve object dependencies.

How does C# support multiple inheritance?
Answer
C# does not directly support multiple inheritance of classes. Classes in C# can only inherit from one base class. However, C# allows multiple inheritance through interfaces, since a class can implement more than one interface.

When a class implements multiple interfaces, it essentially inherits the behavior of each interface, and each interface can be thought of as a contract that the class must abide by. This approach to multiple inheritance provides flexibility while avoiding the complexities and ambiguities that multiple class inheritance can create.

example:

public interface IEngine
{
    
    
    void StartEngine();
}

public interface IDriver
{
    
    
    void Drive();
}

public class Car : IEngine, IDriver
{
    
    
    public void StartEngine()
    {
    
    
        Console.WriteLine("Car engine started.");
    }

    public void Drive()
    {
    
    
        Console.WriteLine("Car is being driven.");
    }
}

// Usage:
Car car = new Car();
car.StartEngine();
car.Drive();

In this example, Car implements the IEngine and IDriver interfaces to provide multiple inheritance-like functionality.

What is method overloading in C#?
Answer
Method overloading is a feature in C# that allows a class to have multiple methods with the same name but different parameter lists. The correct method is called at compile time based on the arguments provided. Method overloading is a way to achieve compile-time polymorphism. The method's return type does not take into account overloading. Method signatures, i.e. method names and parameter lists must be unique.

Here is an example:

public class Calculator
{
    
    
    public int Add(int x, int y)
    {
    
    
        return x + y;
    }

    public double Add(double x, double y)
    {
    
    
        return x + y;
    }

    public int Add(int x, int y, int z)
    {
    
    
        return x + y + z;
    }
}

In the above example, we overloaded the Add method with a different parameter list.

That's it, folks! These 20 questions for newbies to C# are just the beginning.

Stay tuned with me as I share more C# interview questions for all skill levels, from novice to seasoned pro.

Don't forget to follow so you can stay informed. Let's come to C# together!

Guess you like

Origin blog.csdn.net/qq_52010446/article/details/131426312