Skip to main content

C# : Interview questions (91-95)


 Questions:

  • How do you implement a switch statement with pattern matching in C#?
  • What are attributes in C#?
  • How do you define custom attributes in C#?
  • Explain the use of reflection in C#.
  • What is the difference between "typeof" and "GetType()" in C#?
Answers:

1. Implementing a Switch Statement with Pattern Matching in C#:

Pattern matching in switch statements allows you to match against the type and properties of an object. This can make your code more readable and expressive.

public abstract class Shape { }

public class Circle : Shape
{
    public double Radius { get; set; }
}

public class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }
}

public static string GetShapeInfo(Shape shape)
{
    return shape switch
    {
        Circle c => $"Circle with radius {c.Radius}",
        Rectangle r => $"Rectangle with width {r.Width} and height {r.Height}",
        _ => "Unknown shape"
    };
}

// Usage
Shape shape1 = new Circle { Radius = 5.0 };
Shape shape2 = new Rectangle { Width = 4.0, Height = 6.0 };
Shape shape3 = new Shape();

Console.WriteLine(GetShapeInfo(shape1)); // Output: Circle with radius 5
Console.WriteLine(GetShapeInfo(shape2)); // Output: Rectangle with width 4 and height 6
Console.WriteLine(GetShapeInfo(shape3)); // Output: Unknown shape

In this example, the GetShapeInfo method uses a switch expression with pattern matching to determine the type of shape and extract its properties.

2. Attributes in C#:

Attributes in C# are metadata annotations that provide additional information about program elements such as classes, methods, and properties. They can be used for various purposes like controlling serialization, specifying documentation, or providing hints to the compiler.

3. Defining Custom Attributes in C#:

To define a custom attribute, you create a class that inherits from System.Attribute.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorAttribute : Attribute
{
    public string Name { get; }
    public double Version { get; }

    public AuthorAttribute(string name, double version)
    {
        Name = name;
        Version = version;
    }
}

// Applying the custom attribute
[Author("John Doe", 1.0)]
public class SampleClass
{
    [Author("Jane Smith", 1.1)]
    public void SampleMethod() { }
}

In this example, the AuthorAttribute class is defined with Name and Version properties. The attribute is then applied to a class and a method.

4. Use of Reflection in C#:

Reflection in C# allows you to inspect and interact with metadata about types at runtime. It can be used to examine the contents of an assembly, create instances of types, and invoke methods.

using System;
using System.Reflection;

public class SampleClass
{
    public void PrintMessage(string message)
    {
        Console.WriteLine(message);
    }
}

// Usage
Type type = typeof(SampleClass);
MethodInfo methodInfo = type.GetMethod("PrintMessage");
object instance = Activator.CreateInstance(type);
methodInfo.Invoke(instance, new object[] { "Hello, Reflection!" });
// Output: Hello, Reflection!

In this example, reflection is used to get the PrintMessage method of the SampleClass type, create an instance of SampleClass, and invoke the PrintMessage method with a parameter.

5. Difference Between typeof and GetType() in C#:

  • typeof: Used to get the Type object for a type at compile-time.
Type type = typeof(SampleClass);
Console.WriteLine(type.Name); // Output: SampleClass
  • GetType(): Used to get the Type object for an instance at runtime.
SampleClass instance = new SampleClass();
Type type = instance.GetType();
Console.WriteLine(type.Name); // Output: SampleClass

In summary, typeof is used with type names to get the Type object at compile-time, while GetType() is called on an instance to get its Type object at runtime.

These explanations and examples should help you understand how to implement a switch statement with pattern matching, define and use custom attributes, use reflection, and the differences between typeof and GetType() in C#.

C# : Interview questions (96-100)

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