Skip to main content

C# : Interview questions (56-60)

 

Questions :

  • How do you implement a property with both get and set accessors?
  • Explain the difference between a property and a field.
  • What is the purpose of the "this" keyword in C#?
  • How do you create an indexer in C#?
  • What is the purpose of the "base" keyword in C#?
Answers :

1. Implementing a Property with Both Get and Set Accessors:
A property in C# can have both get and set accessors to encapsulate the access to a private field. The get accessor is used to return the property value, and the set accessor is used to assign a new value to the property.

public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

In this example, the Name property encapsulates the private field name. The get accessor returns the value of name, and the set accessor assigns a new value to name.

2. Difference Between a Property and a Field:

  • Field:
    • A field is a variable declared directly in a class or struct.
    • Fields can be public, private, protected, or internal.
    • Fields are accessed directly.
public class Person
{
    public string name; // Field
}
  • Property:
    • A property provides a controlled way to access the private fields of a class.
    • Properties can include logic in their accessors.
    • Properties can be read-only, write-only, or read-write.
    • Properties use get and set accessors.
public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

3. Purpose of the "this" Keyword in C#:

The this keyword in C# refers to the current instance of the class. It is used to access members (fields, properties, methods) of the current instance, especially when there is a naming conflict between method parameters and class members.

public class Person
{
    private string name;

    public void SetName(string name)
    {
        this.name = name; // "this" refers to the current instance's "name" field
    }
}

In this example, the this keyword distinguishes the name field of the current instance from the name parameter of the SetName method.

4. Creating an Indexer in C#:

An indexer in C# allows an object to be indexed like an array. Indexers are defined using the this keyword followed by square brackets.

public class StringCollection
{
    private string[] collection = new string[10];

    public string this[int index]
    {
        get { return collection[index]; }
        set { collection[index] = value; }
    }
}

In this example, the StringCollection class has an indexer that allows access to the collection array using an index.

5. Purpose of the "base" Keyword in C#:

The base keyword in C# is used to access members of the base class from within a derived class. It can be used to call base class constructors, methods, or access fields and properties.

public class BaseClass
{
    public void Display()
    {
        Console.WriteLine("Base class method");
    }
}

public class DerivedClass : BaseClass
{
    public void Show()
    {
        base.Display(); // Call method from base class
        Console.WriteLine("Derived class method");
    }
}

In this example, the base keyword is used in the Show method of the DerivedClass to call the Display method from the BaseClass.

These explanations and examples should help you understand the implementation and use of these concepts in C#.

C# : Interview questions (61-65)

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

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

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