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

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

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...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...