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

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...