Skip to main content

Posts

Showing posts from November, 2016

Extension Method for returning default values

Extension Method for returning default values static class ExtensionsThatWillAppearOnEverything { public static T IfDefaultGiveMe < T >( this T value , T alternate ) { if ( value . Equals ( default ( T ))) return alternate ; return value ; } } var result = query . FirstOrDefault (). IfDefaultGiveMe ( otherDefaultValue ); Or we can use the one shown below ,though its not an extension method. var result = query . FirstOrDefault () ?? otherDefaultValue ;

Extension Methods in C#

Extension Methods in C# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExtensionMethodsSample {     using MyExtensionMethod;     class Program     {          static void Main(string[] args)         {             string firstName = "Anish";             var res = firstName.MySampleExtensionMethod();             Console.ReadLine();         }     } } namespace MyExtensionMethod {     public static class MyExtensionMethod {          public static string MySampleExtensionMethod(this string inputString)         {             return inputString.ToUpperInvariant();         }     } ...