Question: What is the purpose of the 'as' operator in C#?
|
Answer: The 'as' operator is used for explicit type casting in C#.
It attempts to cast an object to a specified type and returns null if the cast fails,
rather than throwing an exception like the traditional cast operator.
|
Question: How attributes are declared and used in C#?
|
Answer: In C# attributes provide a way to add metadata, such as additional information or behavior,
to types and members in C#. They are typically used for declarative programming, allowing developers to attach
descriptive information to code elements and access it at runtime using reflection.
Attributes are defined using the 'Attribute' suffix (e.g., [Serializable], [Obsolete]). Example:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)]
public class SimpleAttribute : Attribute
{
..
}
[Simple] class Class1 {..}
[Simple] interface Interface1 {..}
|
Question: What is the purpose of the 'sealed' keyword in C#?
|
Answer: The 'sealed' keyword is used to prevent a class from being inherited.
When applied to a class, it indicates that the class cannot be used as a base class for
further inheritance, making it effectively final.
|
Question: What is a delegate in C#?
|
Answer: A delegate in C# is a type that represents references to methods with a specific signature.
Delegates allow methods to be passed as parameters to other methods, stored as fields, and invoked dynamically.
They are commonly used for implementing callback mechanisms, event handling, and asynchronous programming.
|
Question: What is a 'ternary operator' in C#?
|
Answer: The ternary operator (?:) is a conditional operator in C# that evaluates a
Boolean expression and returns one of two values depending on whether the expression evaluates to true or false.
It is a shorthand way of writing an if-else statement and is often used for assigning values based on conditions. Example:
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
|
Question: What is an abstract class in C#?
|
Answer: An abstract class in C# is a class that cannot be instantiated directly and
may contain abstract methods, which are methods without a method body.
Abstract classes are intended to serve as base classes for other classes and provide
a template for their behavior. Subclasses of an abstract class must provide implementations for all its abstract methods.
|