What are Extension Methods?
Extension Methods are a language feature that allow you to add methods to an existing type (class, struct, interface, etc). In a language like C#, an Extension Method has at least one parameter (this), which represents the object to operate on. Extension Methods are static methods that are called like class methods. That means that the object it operates on, does not need to be passed to it. Instead it is called on the object itself. Here is a C# example that executes code only if the object it is called on is of a certain type:
public static void IfType<T>(this object item, Action<T> action) where T : class { if (item is T) { action(item as T); } }
Which then can be called like this:
employee.IfType<Manager>(x => x.ActBusy());
Extension Methods are supported in popular languages like C#, Java, Visual Basic, Ruby, F#, Kotlin and many more. This website has a collection of Extension Methods for C#, Visual Basic, F# and Javascript. All Extension Methods in our database have source code and an example how to use it. We invite people to discuss all submitted code to keep a high standard.
So what are you waiting for? Dig up your favourite Extension Method and add it to the database!
Recently Added Extension Methods
-
.RemoveExtraWhitespace();
Removed extra whitespace from a string for NET8 and higher.
-
SqlClient wrapper for reading DateOnly
A wrapper to work with DateOnly for a SqlDataReader which is available starting with .NET Core 6. The example as an aside shows a secondary extension for asynchronous read for strings.
-
SplitOnUpperCase
Useful for display things like property names like FirstName to First Name.
-
Fast Debug For Visual Studio
Prints the message in debug screen in visual studio. Short way for debugging by a short name (p). p means print
-
SkipFrom
Bypasses a specified number of elements in a sequence from a given start position
-
IsEmptyOrWhiteSpace
This method will check if a string is empty or consists only of whitespace characters, but not null or containing any other characters. This check is sometimes required in data validation processes.
-
CheckedList<T>
Provides a generic method to retrieve checked items in a CheckedListBox where the CheckedListBox has been loaded with a list of T. In the example provided a record is used while in another case the source might be a class that represents a record from a database.
-
Difference
Calculates the difference between two strings, returning the remainder of the second string starting from where it differs from the first.
-
IsNullOrEmpty
Indicates whether the specified array is null or empty (has no items). Returns true if the array parameter is null or empty; otherwise, false.
-
ToListado
Convierte un DataTable a un Listado de un Tipo Especifico.
-
HasTables
Determina si un DataSet tiene DataTables con Datos.
-
SplitIn
Convierte una Cadena con Números separados por un carácter a un Listado de Números de un Tipo Especifico.
-
ToDictionario
Convierte una clase a un Dictionary
-
HasItems
Determina si un Listado Tiene Items.
-
HasRows
Determina si un DataTable Tiene DataRows.
-
GetValueOrDefinedDefault
Given our dictionary retrieves the element with a given key defined in input. when this key is not defined, or the dictionary is null, or the key itself is null, then the default value also defined in input is returned
-
DateTimeCheckValve
this ExtensionMethod check if startdate is null reutrn the min value of datetime and if the end date is null return the max value
-
String to Guid
This is used to be common in web api's. When you must to receive the guid as a string in parameter.
-
Dictionary<K,V>.GetValueOrDefault()
If you attempt to get a value from a dictionary using a key that doesn't exist, it throws a KeyNotFoundException. But this extension method to return a default value when the key doesn't exist. Also supports an overload with a Lazy initialization of the fallback value.
-
Repeated
Extremely fast string repeater complete with alternate extension for char spans.
-
DistinctCsv
Returns a distinctive comma-separated list.
-
FirstDayOfMonth
Return the first day of the mounth for a given date
-
Maximum number in Array of Random Numbers
Make an array of generated random numbers and get the maximum number every time you run.
-
TryAdd
You should have this already: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.tryadd?view=net-7.0 but this is not always available in all environments.
-
Fluent DateOnly Extensions
A fluent way to create DateOnly values.
-
AnyOfType
Determines if there is an element of a given type inside a collection.
-
ToLocalCurrencyString
Convert a double to a string formatted to the specified CultureInfo or the Default CultureInfo if null.
-
EnsureEndsWith
Ensures that a string ends with a given suffix.
-
EnsureStartsWith
Ensures that a string starts with a given prefix.
-
AnyAndAll
Determines whether a sequence contains any elements and whether all elements of a sequence satisfy a condition. The normal 'All' method returns true when the sequence is empty.
-
EnumerateWithIndex<T>()
Enumerate an IEnumerable<T> source and getting the Index and the Item returned in a ValueTuple.
-
ForEachRef
Performs the specified action on each ValueType in the List<T> without copying it.
-
Divide decimal currency evenly
Division where reminder is redistributed among results so that average delta is minimal.
-
TryGetNonEnumeratedCount
Attempts to determine the number of elements in a sequence without forcing an enumeration. For those who are not yet using .NET 6
-
ToList<T>
This extentions method will convert the ObservableCollection object to List of underluying objects.
-
DistinctBy
Extension method to distinct by specific property.
-
RemoveSpecialChar
Find and remove any special char, only letting numbers and letters in.
-
How to show data more smoothly in DataGridView (simple)?
In C# programming with winform, when you display data on DataGridView with a large number of rows and columns, every time you drag the row, scroll the column, the DataGridView will be jerky and laggy. How can we make it show data more smoothly? There are many ways and of course Basiap will guide you in the simplest way. One hit applies to all of your DataGridView. More informations at: http://basiap.com/thong-tin/kien-thuc-cong-nghe/lap-trinh-c-tang-hieu-suat-load-du-lieu-cua-datagridview-len-10-lan
-
Enum.GetDescription
获取项目中分配给 Enum 的描述属性。
-
Next
Get next day of the week
-
Sort
Sort Dictionary by Key or Value, Ascending/descending
-
FormatVar
Like format type. Source: https://www.extensionmethod.net/csharp/string/withvar
-
StartEnumerable
Creates an IEnumerable from a list of single entities in a Fluent-manner.
-
DoubleBuffered
fast scroll for datagridview
-
FastSum
Sum decimals
-
WhereNotNull
I’m a big fan of the Nullable Reference Types feature added in C# 8.0. It lets the compiler catch a bunch of potential runtime errors, and I guarantee if you turn it on you’ll get a bunch of warnings. As of .NET 5.0, the entire BCL is now covered with nullable annotations, and a lot of the extended ecosystem supports them too. But there are situations where the compiler is unable to work out that you’ve done a null check, meaning you either have to use the “null-forgiving operator” (where you append a bang to the identifier, like item!.Name), disable the null checking, or just ignore the warning. The WhereNotNull extension method filters out nulls and changes the expression type accordingly. source: https://rendle.dev/posts/where-not-null/
-
FillSpan
Fill any Span using an IEnumerable. Returns the number of items which are placed in the Span.
-
System.Func<bool> CheckAll
Runs through the Func<bool>.GetInvocationList() passing in the argument to each and returning an Or'd or And'd result.
-
System.Func<bool> CheckAll
Runs through the Func<bool>.GetInvocationList() passing in the argument to each and returning an Or'd or And'd result.
-
Dictionary AddRange
Add an enumeration of items to a dictionary. There are times when you may want to simply add to a dictionary at different points in the pipe, instead of always creating it from a given set of entities This extension allows you to add items to a dictionary from a select statement, or some other enumerable.