20 Mar 2024
Intermediate
Extension methods in C# allow you to add new methods to existing types without altering their source code or inheritance hierarchy. These methods are defined as static methods in separate classes and can be invoked as if they were instance methods of the extended type.
Examples of extension methods with explanations of their usage:
- ToUpperFirstLetter: An extension method that capitalizes the first letter of a string.
public static class StringExtensions
{
public static string ToUpperFirstLetter(this string str)
{
if (string.IsNullOrEmpty(str))
return str;
return char.ToUpper(str[0]) + str.Substring(1);
}
}
// Usage
string text = "hello world";
string capitalizedText = text.ToUpperFirstLetter();
Console.WriteLine(capitalizedText); // Output: "Hello world"
- IsNumeric: An extension method that checks if a string represents a numeric value.
public static class StringExtensions
{
public static bool IsNumeric(this string str)
{
double result;
return double.TryParse(str, out result);
}
}
// Usage
string input = "123";
bool isNumeric = input.IsNumeric();
Console.WriteLine(isNumeric); // Output: true
- DaysSince: An extension method that calculates the number of days between a given date and today's date.
public static class DateTimeExtensions
{
public static int DaysSince(this DateTime date)
{
TimeSpan span = DateTime.Today - date.Date;
return span.Days;
}
}
// Usage
DateTime someDate = new DateTime(2023, 1, 1);
int daysSince = someDate.DaysSince();
Console.WriteLine(daysSince); // Output: Number of days since 2023-01-01 till today
-IsAdult: An extension method that determines if a person is considered an adult based on their age.
public static class DateTimeExtensions
{
public static bool IsAdult(this DateTime birthDate)
{
int age = DateTime.Today.Year - birthDate.Year;
if (DateTime.Today < birthDate.AddYears(age))
age--;
return age >= 18;
}
}
// Usage
DateTime birthDate = new DateTime(2000, 1, 1);
bool isAdult = birthDate.IsAdult();
Console.WriteLine(isAdult); // Output: true or false based on age
- GetFileExtension: An extension method that extracts the file extension from a file path.
public static class StringExtensions
{
public static string GetFileExtension(this string filePath)
{
if (string.IsNullOrEmpty(filePath))
return string.Empty;
int lastIndex = filePath.LastIndexOf('.');
if (lastIndex == -1)
return string.Empty;
return filePath.Substring(lastIndex + 1);
}
}
// Usage
string filePath = "path/to/file.txt";
string extension = filePath.GetFileExtension();
Console.WriteLine(extension); // Output: "txt"
These examples demonstrate how extension methods can be used to add custom functionality to existing types, making code more readable and maintainable.