Wednesday, October 30, 2024
Delegate and Event, Additional FAQs
Attribute in C#, Additional FAQs
Question1
Sunday, October 27, 2024
How can you call a method of base class in derived class in C#?
Difference between IEnumerable and IEnumerator in C#
Difference between TryParse and Parse in C#
Custom Exception in C#
C# Custom Attribute Example
using System;
// Define a custom attribute called "AuthorAttribute" that can be applied to classes and methods.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorAttribute : Attribute
{
public string Name { get; }
public AuthorAttribute(string name)
{
Name = name;
}
}
// Apply the custom attribute to a class and a method.
[Author("John Doe")]
class MyClass
{
[Author("Alice Smith")]
public void MyMethod()
{
Console.WriteLine("Hello, world!");
}
}
class Program
{
static void Main()
{
// Use reflection to access and display the custom attribute values.
Type myClassType = typeof(MyClass);
object[] classAttributes = myClassType.GetCustomAttributes(typeof(AuthorAttribute), false);
if (classAttributes.Length > 0)
{
AuthorAttribute classAuthorAttribute = (AuthorAttribute)classAttributes[0];
Console.WriteLine($"Author of MyClass: {classAuthorAttribute.Name}");
}
var myMethod = typeof(MyClass).GetMethod("MyMethod");
object[] methodAttributes = myMethod.GetCustomAttributes(typeof(AuthorAttribute), false);
if (methodAttributes.Length > 0)
{
AuthorAttribute methodAuthorAttribute = (AuthorAttribute)methodAttributes[0];
Console.WriteLine($"Author of MyMethod: {methodAuthorAttribute.Name}");
}
}
}
- We define a custom attribute called AuthorAttribute that takes a string parameter in its constructor.
- We apply this custom attribute to both a class (MyClass) and a method (MyMethod) using square brackets.
- In the Main method, we use reflection to access the custom attribute values for the MyClass and MyMethod. We retrieve the attribute objects and extract the Name property to display the author's name.
Author of MyClass: John Doe
Author of MyMethod: Alice Smith
Saturday, October 26, 2024
C# Delegates and Events in depth
C# Task class, Asynchronous and Parallel Tasks
In C#, tasks are used to represent asynchronous operations. They are part of the Task Parallel Library (TPL) and provide a way to perform work asynchronously on a separate thread. Creating a task in C# involves using the Task class or related methods. Here are the common ways to create a task:
C# Type class and Reflextion
What is use of Type class in C#?
C# Enum In Depth
C# Verbatim String Literal
string path = @"C:\s\name\Documents";
string path = "C:\\s\\name\\Documents";
Different ways to create an instance of class in C#
1. Using the new Keyword:
The most common way to create an instance of a class is using the new keyword followed by the class name, followed by parentheses (if the class has a parameterless constructor).
MyClass myObject = new MyClass(); // Creating an instance using a parameterless constructor
2. Using Constructors with Parameters:
If the class has constructors with parameters, you can use these constructors to initialize the instance.
MyClass myObject = new MyClass("parameter1", 42); // Creating an instance using a constructor with parameters
3. Using Object Initializer:
This approach allows you to set the properties of the object after it's created using an initializer syntax.
MyClass myObject = new MyClass{
Property1 = "value1",
Property2 = 42
};
4. Using Factory Methods:
You can define static or instance methods within the class or a separate factory class to create and return instances of the class.
public class MyClass
{
public static MyClass CreateInstance()
{
return new MyClass();
}
}
MyClass myObject = MyClass.CreateInstance();
5. Using Object Cloning:
If your class implements ICloneable interface or provides a custom cloning mechanism, you can create a new instance by cloning an existing object.
MyClass myObject = originalObject.Clone();
6. Using Activator.CreateInstance:
The Activator class provides a generic method to create instances of a type, even when the type is not known at compile time.
MyClass myObject = Activator.CreateInstance();
7. Using Reflection:
You can use reflection to create an instance of a class dynamically, especially when the class type is determined at runtime.
Type classType = Type.GetType("Namespace.MyClass");
MyClass myObject = (MyClass)Activator.CreateInstance(classType);
It's important to choose the appropriate approach based on the requirements of your application and the design principles you want to follow.
Records in C# Explained
Here are the key aspects and features of records in C#:
1. Immutable by Default:
Records are immutable by default, meaning their values cannot be modified after creation. This is essential for creating reliable and predictable data structures.
2. Data-Centric:
Records are designed to represent data, making them an excellent choice for modeling objects that primarily hold data without behavior.
3. Concise Syntax:
C# records offer a concise syntax for defining properties and initializing their values. You can define a record using the record keyword, followed by the record's name and its properties.
public record Person(string FirstName, string LastName);
4. Property Definitions:
Properties in a record are defined directly within the record declaration. The properties are implicitly read-only, meaning you cannot assign new values to them once the record is created.
5. Value Equality:
Records automatically implement value equality based on their property values. This means two record instances with the same property values are considered equal.
6. Deconstructor:
Records provide a deconstructor, which allows you to easily destructure a record into its constituent properties.
7. Inheritance and Overriding:
Records can inherit from other classes and interfaces, and you can override methods, including ToString(), GetHashCode(), and Equals().
Here's a simple example of using a record:
public record Person(string FirstName, string LastName);
class Program
{
static void Main()
{
Person person1 = new Person("John", "Doe");
Person person2 = new Person("John", "Doe");
Console.WriteLine(person1.Equals(person2)); // Outputs: True
// Deconstruction
var (firstName, lastName) = person1;
Console.WriteLine($"First Name: {firstName}, Last Name: {lastName}");
}
}
Custom Constructor in Records
In C#, records are a special kind of type introduced in C# 9.0 that provides a succinct way to declare a type and is often used to model immutable data. Records automatically provide a default constructor, which initializes the properties of the record.
However, records in C# do not allow you to define a custom constructor explicitly. The default constructor is provided by the language and automatically initializes the properties based on the values provided during object creation.
Here's an example of a record in C#:
public record Person(string FirstName, string LastName);
In this example, a Person record is defined with two properties: FirstName and LastName. The default constructor for this record is automatically provided by the compiler.
If you need custom initialization logic for your record, you can still use methods or factory methods to achieve the desired behavior:
public record Person(string FirstName, string LastName)
{
public Person(string fullName)
{
var parts = fullName.Split(' ');
FirstName = parts.Length > 0 ? parts[0] : string.Empty;
LastName = parts.Length > 1 ? parts[1] : string.Empty;
}
}
In this modified example, we have added a custom constructor Person(string fullName) that takes a full name and initializes the FirstName and LastName properties accordingly.
Keep in mind that records are primarily designed for immutability and straightforward data representation, so complex initialization logic is generally better suited for methods or factory methods.
C# Event Definition
Can event be defined in record in C#?
In C#, events cannot be defined directly within a record type. Records are designed to be lightweight data structures that represent immutable values, and they are primarily used for data storage and retrieval. Events, on the other hand, are mechanisms used to provide notifications or callback functionality when something happens in a class or object.
If you need to define events in your C# code, you typically do so within a class rather than a record. Here's an example of how you would define an event within a class:
public class MyClass
{
public event EventHandler MyEvent;
public void DoSomething()
{
// Trigger the event when something happens
MyEvent?.Invoke(this, EventArgs.Empty);
}
}
In this example, MyClass has an event called MyEvent, and you can subscribe to this event and handle its occurrences in other parts of your code.
Records are more suitable for scenarios where you want to define simple data structures with value semantics and automatic implementations of equality, immutability, and other features. Events are typically associated with classes that represent behavior or functionality.
If you need a combination of events and data storage, you can use a class to encapsulate both your data and event-handling logic.
What are different ways to call a method in C#?
1. Direct Method Call:
This is the most common way to call a method. You simply specify the method name followed by parentheses and any required arguments.
methodName(argument1, argument2);
2. Calling Static Methods:
For static methods, you can call the method directly using the class name.
ClassName.MethodName(argument1, argument2);
3. Calling Instance Methods:
For instance methods, you need to create an instance of the class and then call the method on that instance.
ClassName instance = new ClassName();
instance.MethodName(argument1, argument2);
4. Method Chaining:
If a method returns an object of the same class, you can chain method calls together.
instance.Method1().Method2().Method3();
5. Using Delegates:
Delegates allow you to store and call a reference to a method. You can invoke the delegate to call the method.
delegateType delegateName = methodName;
delegateName(argument1, argument2);
6. Using Lambda Expressions:
You can create and call methods using lambda expressions, especially for delegates or functional interfaces.
delegateType delegateName = (arg1, arg2) => { /* method implementation */ };
delegateName(argument1, argument2);
7. Using the Invoke Method:
For delegates, you can use the Invoke method to call the referenced method.
delegateName.Invoke(argument1, argument2);
8. Using Event Handlers:
Event handlers are methods that are called when a specific event occurs. They are usually subscribed to events in the application.
eventName += methodName; // Subscribe the method to the event
9. Using Named Arguments:
You can specify arguments by their parameter names, allowing you to provide them in a different order or omit some optional parameters.
methodName(parameter2: value2, parameter1: value1);
These are some of the common ways to call methods in C#. The choice of method calling approach depends on the specific requirements and design of your application.
Partial class in C#
A partial class in C# allows you to split the definition of a class, struct, interface, or method across multiple files. This can be useful when working on large projects or when using auto-generated code, as it allows for organizing code in a way that separates auto-generated and manually written parts of the class. The partial keyword is used to specify that a class has been divided into parts.
Key Features of Partial Classes
- Organizational Clarity: Keeps code cleaner by separating different functionalities or generated code from manually written code.
- Team Collaboration: Multiple team members can work on the same class in different files without merging conflicts.
- Auto-generated Code: Useful in cases where tools like Visual Studio generate code for you, as in Windows Forms or Entity Framework.
How to Use Partial Classes
To define a partial class, declare it using the partial keyword in each file where the class definition is split. Each file must have the same class name and be in the same namespace.
Example of Partial Class
Suppose you have a class Person split into two files, Person1.cs and Person2.cs:
public partial class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string GetFullName()
{
return $"{FirstName} {LastName}";
}
}
File: Person2.c
public partial class Person
{
public int Age { get; set; }
public void DisplayInfo()
{
Console.WriteLine($"Name: {GetFullName()}, Age: {Age}");
}
}
Both parts together make up the complete Person class, with FirstName, LastName, Age, and methods GetFullName and DisplayInfo.
Points to Remember
- All parts must use the partial keyword.
- All parts must have the same accessibility level (e.g., public, internal).
- If partial classes contain conflicting members, a compilation error will occur.
- The compiler combines all parts into a single class during compilation.
Use Cases
- Generated Code: Typically used when tools or frameworks generate part of the class.
- Large Classes: Split functionality for better organization, especially in large classes.
Partial classes are mainly used to improve code readability and maintainability, especially in projects where auto-generated code is prevalent or when dealing with large classes.
Partial Method Declaration, Implementation and Usage in C#
partial void MyPartialMethod(int x);
partial void MyPartialMethod(int x)
{
// Implementation code here
}
public void SomeMethod()
{
// Call the partial method
MyPartialMethod(42);
}
partial void MyPartialMethod(int x);
partial void MyPartialMethod(int x, string message = "Default message");
partial void MyPartialMethod(int x);
partial void MyPartialMethod(int x) // Valid, matching signature
{
// Implementation code here
}
// Error: Multiple partial method declarations with the same name and signature
partial void MyPartialMethod(int x);
partial void MyPartialMethod(int x);
// Error: Multiple partial method implementations with the same name and signature
partial void MyPartialMethod(int x)
{
// Implementation 1
}
partial void MyPartialMethod(int x)
{
// Implementation 2
}
Extension method and use it in C#
Objectives:
- What is Extension Method
- How to create Extension methods
- How to use Extension Method
using System;
public static class StringExtensions
{
public static string Reverse(this string str)
{
char[] charArray = str.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
using System;
class Program
{
static void Main(string[] args)
{
string originalString = "hello";
string reversedString = originalString.Reverse();
Console.WriteLine("Original: " + originalString);
Console.WriteLine("Reversed: " + reversedString);
}
}
Is Nested Interface allowed in C#
public interface IBaseInterface
{
void SomeMethod();
}
public interface IDerivedInterface : IBaseInterface
{
void AnotherMethod();
}
Nested classes with example in C#
using System;
public class OuterClass
{
private int outerData;
public OuterClass(int data)
{
outerData = data;
}
public void DisplayOuterData()
{
Console.WriteLine("Outer data: " + outerData);
}
public class NestedClass
{
private int nestedData;
public NestedClass(int data)
{
nestedData = data;
}
public void DisplayNestedData()
{
Console.WriteLine("Nested data: " + nestedData);
}
public void AccessOuterData(OuterClass outer)
{
Console.WriteLine("Accessing outer data from nested class: " + outer.outerData);
}
}
}
public class Program
{
public static void Main()
{
// Creating an instance of the outer class
OuterClass outer = new OuterClass(10);
// Creating an instance of the nested class
OuterClass.NestedClass nested = new OuterClass.NestedClass(20);
// Accessing and displaying data from the outer and nested classes
outer.DisplayOuterData();
nested.DisplayNestedData();
// Accessing outer data from the nested class
nested.AccessOuterData(outer);
}
}
- OuterClass is the outer class that contains the nested class NestedClass.
- NestedClass is a nested class within OuterClass.
- NestedClass has access to the private members of OuterClass, such as outerData.
- The Main method demonstrates creating instances of both the outer and nested classes and accessing their members.
Hot Topics
-
In this post we will learn what is stored procedure, how it is different from query and what are its advantages over queries. Procedures I...
-
Objectives To provide detailed information about ListBox Types of ListBox Using ListBox in VBA applications Please read the post till end...
-
ACID Properties To understand transaction in depth, we must know all about its properties. We will look at ACID properties which are rela...