Skip to main content

C# : Interview questions (81-85)

 

Questions:

    • What is the purpose of the "as" keyword in C#?
    • Explain the difference between "as" and "is" keywords in C#.
    • What is the purpose of the "nameof" operator in C#?
    • How do you implement conditional access in C#?
    • What is pattern matching in C#?

    Answers:

    1. Purpose of the "as" Keyword in C#:

    The as keyword in C# is used for safe type casting. It attempts to cast an object to a specified type, and if the cast fails, it returns null instead of throwing an exception. This is useful for avoiding exceptions when you are unsure if the conversion will succeed.

    object obj = "Hello, world!";
    string str = obj as string;
    
    if (str != null)
    {
        Console.WriteLine(str); // Output: Hello, world!
    }
    

    In this example, obj is safely cast to string using the as keyword. If obj were not a string, str would be null.

    2. Difference Between "as" and "is" Keywords in C#:

    • is: Checks if an object is of a specified type and returns true or false.
    object obj = "Hello, world!";
    if (obj is string)
    {
        string str = (string)obj;
        Console.WriteLine(str); // Output: Hello, world!
    }
    
    • as: Attempts to cast an object to a specified type and returns null if the cast fails.
    object obj = "Hello, world!";
    string str = obj as string;
    if (str != null)
    {
        Console.WriteLine(str); // Output: Hello, world!
        
    }
    

    In summary, is is used to check the type, and as is used to cast the type safely.

    3. Purpose of the "nameof" Operator in C#:

    The nameof operator returns the name of a variable, type, or member as a string. It is useful for obtaining the name of a symbol in a type-safe manner, which is particularly helpful in logging, error messages, and code maintenance.

    public class Person
    {
        public string Name { get; set; }
    }
    
    // Usage
    Person person = new Person();
    Console.WriteLine(nameof(person.Name)); // Output: Name
    

    In this example, nameof(person.Name) returns the string "Name".

    4. Implementing Conditional Access in C#:

    Conditional access is implemented using the null-conditional operator ?.. It allows you to safely access members and elements only when the object is not null, preventing NullReferenceException.

    Person person = null;
    string name = person?.Name; // name will be null if person is null
    
    Person person2 = new Person();
    string name2 = person2?.Name; // name2 will be the value of person2.Name if person2 is not null
    

    In this example, the ?. operator safely accesses the Name property only if person is not null.

    5. Pattern Matching in C#:

    Pattern matching in C# enhances type checking and casting capabilities, allowing for more readable and concise code. It can be used with the is keyword, switch statements, and more.

    Using is with Pattern Matching:

    object obj = "Hello, world!";
    if (obj is string str)
    {
        Console.WriteLine(str); // Output: Hello, world!
    }
    

    In this example, the is keyword checks the type and declares a variable of that type in one step.

    Using Pattern Matching in switch Statements:

    public static string GetShapeType(object shape)
    {
        switch (shape)
        {
            case Circle c:
                return $"Circle with radius {c.Radius}";
            case Rectangle r:
                return $"Rectangle with width {r.Width} and height {r.Height}";
            default:
                return "Unknown shape";
        }
    }
    
    public class Circle
    {
        public double Radius { get; set; }
    }
    
    public class Rectangle
    {
        public double Width { get; set; }
        public double Height { get; set; }
    }
    
    // Usage
    object shape = new Circle { Radius = 5 };
    Console.WriteLine(GetShapeType(shape)); // Output: Circle with radius 5
    

    In this example, pattern matching is used in a switch statement to identify the type of the shape object and extract its properties.

    These explanations and examples should help you understand the purpose and usage of the as keyword, the difference between as and is, the nameof operator, conditional access, and pattern matching in C#.

    C# : Interview questions (86-90)

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

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

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