Skip to main content

C# : Interview questions (71-75)


Questions:

  • What is a generic method?
  • Explain the use of constraints in generics.
  • What is covariance and contravariance in generics?
  • What are anonymous types in C#?
  • How do you implement anonymous methods in C#?
Answers:

1. What is a Generic Method?

A generic method in C# is a method that is defined with a type parameter. This allows the method to operate on different data types without needing to be rewritten for each type. Generic methods provide type safety, reduce code duplication, and improve performance.

public class Utilities
{
    public void Swap<T>(ref T a, ref T b)
    {
        T temp = a;
        a = b;
        b = temp;
    }
}

// Usage
int x = 1, y = 2;
Utilities utilities = new Utilities();
utilities.Swap(ref x, ref y);
Console.WriteLine($"x: {x}, y: {y}"); // Output: x: 2, y: 1

In this example, the Swap method is a generic method that can swap the values of two variables of any type.

2. Use of Constraints in Generics:

Constraints in generics are used to restrict the types that can be used as arguments for a type parameter. This ensures that the type arguments meet certain requirements, providing more control over the behavior of generic classes and methods.

public class Utilities
{
    // Constraint to ensure T implements IComparable<T>
    public T Max<T>(T a, T b) where T : IComparable<T>
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
}

// Usage
Utilities utilities = new Utilities();
int maxInt = utilities.Max(10, 20);
string maxString = utilities.Max("apple", "banana");
Console.WriteLine($"Max Int: {maxInt}, Max String: {maxString}"); // Output: Max Int: 20, Max String: banana

In this example, the Max method has a constraint that ensures the type parameter T implements IComparable<T>, allowing the method to compare values of type T.

3. Covariance and Contravariance in Generics:

  • Covariance: Allows a generic type to be assigned to another generic type with a more derived type parameter. It is applicable to reference types and is denoted using the out keyword.
IEnumerable<string> strings = new List<string>();
IEnumerable<object> objects = strings; // Covariance
  • Contravariance: Allows a generic type to be assigned to another generic type with a less derived type parameter. It is applicable to reference types and is denoted using the in keyword.
Action<object> actionObject = (object obj) => Console.WriteLine(obj);
Action<string> actionString = actionObject; // Contravariance

In these examples, covariance allows an IEnumerable<string> to be assigned to an IEnumerable<object>, and contravariance allows an Action<object> to be assigned to an Action<string>.

4. Anonymous Types in C#:

Anonymous types in C# provide a way to create a new type without explicitly defining it. They are primarily used for convenience in scenarios where defining a new type would be overkill, such as in LINQ queries.

var person = new { Name = "John", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Output: Name: John, Age: 30

In this example, an anonymous type with properties Name and Age is created and assigned to the variable person.

5. Implementing Anonymous Methods in C#:

Anonymous methods in C# provide a way to define inline methods without having to explicitly declare them. They are primarily used in delegate assignments and event handling.

delegate void PrintDelegate(string message);

class Program
{
    static void Main()
    {
        PrintDelegate print = delegate (string message)
        {
            Console.WriteLine(message);
        };

        print("Hello, world!"); // Output: Hello, world!
    }
}

In this example, an anonymous method is assigned to the print delegate, which prints a message to the console.

Alternatively, you can use lambda expressions, which provide a more concise syntax for anonymous methods:

PrintDelegate print = (message) => Console.WriteLine(message);
print("Hello, world!"); // Output: Hello, world!
Both approaches achieve the same result but lambda expressions offer a cleaner and more readable syntax.

Comments

Popular posts from this blog

C# : How can we access private method outside class

Introduction In object-oriented programming, encapsulation is a fundamental principle that restricts direct access to the internal implementation details of a class. Private methods, being part of this internal implementation, are designed to be accessible only within the confines of the class they belong to. However, there might be scenarios where you need to access a private method from outside the class. In this blog post, we'll explore several techniques to achieve this in C#. 1. Reflection: A Powerful Yet Delicate Approach Reflection is a mechanism in C# that allows inspecting and interacting with metadata about types, fields, properties, and methods. While it provides a way to access private methods, it should be used cautiously due to its potential impact on maintainability and performance. using System ; using System . Reflection ; public class MyClass { private void PrivateMethod ( ) { Console . WriteLine ( "This is a private method."

C# : Understanding Types of Classes

In C#, classes serve as the building blocks of object-oriented programming, providing a blueprint for creating objects. Understanding the types of classes and their applications is crucial for designing robust and maintainable software. In this blog, we’ll delve into various types of classes in C#, accompanied by real-world scenarios and code snippets for a practical understanding. 1. Regular (Instance) Classes Definition: Regular classes are the most common type and are used to create instances or objects. They can contain fields, properties, methods, and other members. Example Scenario: A Person class representing individual persons with properties like Name and Age. public class Person { public string Name { get ; set ; } public int Age { get ; set ; } } 2. Static Classes Definition: A static class cannot be instantiated and can only contain static members (methods, properties, fields). It’s often used for utility functions. Example Scenario: A MathUtility cla

C# : 12.0 : Primary constructor

Introduction In C# 12.0, the introduction of the "Primary Constructor" simplifies the constructor declaration process. Before delving into this concept, let's revisit constructors. A constructor is a special method in a class with the same name as the class itself. It's possible to have multiple constructors through a technique called constructor overloading.  By default, if no constructors are explicitly defined, the C# compiler generates a default constructor for each class. Now, in C# 12.0, the term "Primary Constructor" refers to a more streamlined way of declaring constructors. This feature enhances the clarity and conciseness of constructor declarations in C# code. Lets see an simple example code, which will be known to everyone. public class Version { private int _value ; private string _name ; public Version ( int value , string name ) { _name = name ; _value = value ; } public string Ve