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

    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