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#?
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#.
Comments
Post a Comment