Skip to main content

Posts

Showing posts with the label Extension Methods

Different ways of String Reversal in C#

As you may be aware C#'s string class don’t have a Reverse() function by default, so let’s discuss different ways to reverse a given string: Using manual reversal way: The traditional way is to reverse a string by manually looping through it character by character and creating a new string. string inputStr = "This is test string" ; string outputStr = "" ; for ( int i = inputStr.Length - 1; i >= 0; i--) {     outputStr += inputStr[i]; } One thing to remember though, if you are using this approach to reverse a large string then you should use StringBuilder to create output string instead of string because a string instance is immutable and you cannot change it after it was created. Any operation that appears to change the string instead returns a new instance. Using Array.Reverse(): The second approach we can reverse a string is with the inbuilt Array.Reverse() method of Array class. st...

C#: How to get description from Enum value (using Extension method).

To get the description from Enum value we can write our own string extension method and can use that method in same way, we are using other existing methods. We’ll take help of reflection to get description from Enum value. Extension method: using   System; using System.Reflection; using   System. ComponentModel ; public   static   class   EnumExtensions {       public static string GetDescription( this Enum en)     {        var type = en.GetType();        var mInfo = type.GetMember(en.ToString());        if (mInfo.Length > 0)        {             var attrs = mInfo[0].GetCustomAttributes(                  ...

LINQ: Understand the difference between Single vs SingleOrDefault vs First vs FirstOrDefault extension methods

Single(), SingleOrDefault(), First() and FirstOrDefault() are extension methods of the Enumerable class. “These Extension methods are static method that we can call from an instance object which implement IEnumerable interface.” Many people get confused about the difference between Single, SingleOrDefault, First, and FirstOrDefault extension methods in LINQ. Let’s understand the difference between all these methods: Single(): This method searches for single instances in a collection which matching a condition. If the collection has 0 or more than one matching element, we get an exception. This method should be used if you are sure that there will exactly 1 element, for example you can use Single with primary column of an object. SingleOrDefault(): This method returns a single, specific element in a collection, or a default value if that element is not found. If there is no matching element found then by default it’ll return null value. However this method wil...

C#: Extension method to check or validate if a string is a valid Email Address.

To check if a string is valid email address or not we can write our own string extension method and can use that method in same way, we are using other existing methods(i.e. ToString(), ToLower() etc).   Method: using System; using System.Text.RegularExpressions; public static class StringExtensions {     public static bool IsValidEmail( this String Email)     {          var emailRegex = new Regex ( @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +                             @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +                             @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" );          return emailRegex.IsMatch(Email); ...

C#: How to bind an Enum to a ListBox/DropDownList/ Checkboxlist control in ASP.NET?

There have been requirements where we need to bind ListControl from enum (with enum Description as Text and enum value as Value). For example I have an enum of Countries as follows: public enum TestCountries {     [ Description ( "India" )] India = 1     ,     [ Description ( "United State Of America" )] UnitedStateOfAmerica = 2     ,     [ Description ( "United Kingdom" )] UnitedKingdom = 3 } And I want to bind this enum’s description and value to any list control. Here I am writing a static method “LoadListForListControls<T>”, which will take Enum as T, and then return list of ListItem. // We need to use following namespaces for this method: using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Web.UI.WebControls; public static List < L...