-
What is the basic structure of an extension method? Give an example which is used to reverse a string: 'abc' to 'cba'.
Basic structure: A static method within a static class that uses the 'this' keyword to represent the item it is extending.
- public static string Reverse(this string input)
- {
- char[] chars = input.ToCharArray();
- Array.Reverse(chars);
- return new String(chars);
- }
-
What are extension methods? Where would we put it and how would we call it?
An extension method is a special kind of static method located within a static class that don't get instantiated and can extend a data type. They allow you to add methods to existing data types without creating the data type itself using the 'new' keyword.
We typically place them in a folder called Utilities within a root program containing other commonly shared objects. Within another project, this utility can then be referenced and then imported into the file with the using directive.
-
Write a simple Int32 extension method to convert a string value to Int32 (include error handling).
- public static long ToInt32(this string value)
- {
- Int32 result = 0;
- if (!string.IsNullOrEmpty(value))
- Int32.TryParse(value, out result);
- else
- throw new FormatException(string.Format("'{0}' cannot be converted as Int32", input));
-
Write an extension method to format a string into a phone number: (555) 123-1212
- public static string FormatPhone(this string input)
- {
- if (IsPhone(input))
- return string.Format("({0}) {1}-{2}", input.Substring(0, 3), input.Substring(3, 3), input.Substring(7, 4));
- else
- return "(000) 000-0000";
- }
-
Write an extension method to validate if an email address is correctly formatted.
- public static bool IsEmail(this string input)
- {
- var match = Regex.Match(input, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
- return match.Success;
- }
-
Write an extension method to determine if the date provided is a weekend.
- public static bool IsWeekend(this DateTime value)
- {
- return (value.DayOfWeek == DayOfWeek.Sunday || value.DayOfWeek == DayOfWeek.Saturday);
- }
-
Write a boolean extension method which checks if a string is null or empty.
- public static bool IsNullOrEmpty(this string input)
- {
- return (input == null || input == "") ? true : false;
- }
-
Write an extension method used to check and simplify checking for null values.
- public static bool IsNull(this object source)
- {
- return source == null;
- }
-
Write an extension method to return a date if one exists or throw an error.
- public static DateTime ToDate(this string input)
- {
- DateTime result;
- if (!string.IsNullOrEmpty(input))
- DateTime.TryParse(input, out result);
- else
- throw new FormatException(string.Format("'{0}' cannot be converted as DateTime", input));
- return result;
- }
|
|