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
-
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
.GetInvocationList() passing in the argument to each and returning an Or'd or And'd result. -
System.Func<bool> CheckAll
Runs through the Func
.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.
-
AddToList
Given a dictionary where the value type is a List, add items to values of the dictionary, and/or create a list of items as needed, without having to test if the key item already exists.
-
AddToList
Given a dictionary where the value type is a List, add items to values of the dictionary, and/or create a list of items as needed, without having to test if the key item already exists.
-
Quote
Add double quotes to the beginning and end of a string. Not taking into account if there are already quotes available.
-
Penultimate
Gets the penultimate item of a collection
-
Replace char at index
Replace one char at index
-
Like(searchString) & ReverseLike(compareString)
Extension method compareString.Like(searchString) to compare a string using SQL Like style wildcards, and searchString.ReverseLike(compareString). Wildcards like "a", "a%", "%b", "a%b" and "a%b%c" supported.
-
AddIf
Extension that adds an element to a collection only if a given condition is met.
Same as
if (some condition)
collection.Add(element)
-
CompareWithoutMinutes
Compares two datettime objects ignoring minutes and seconds
-
GetStringValue
If your enum member has attribute Display from System.ComponentModel.Annotations you can get this annotation value
-
DistanceTo
Gets the distance between two 2D points where a point is given using the standard .NET Point class in System.Drawing namespace
-
All() and Any() on Array and List<T>
Faster implementations of the LINQ All() and Any() methods for Array and List
. This solution uses less memory allocations and is just faster. Temporary solution until this PR is accepted https://github.com/dotnet/runtime/pull/1832 -
ToLong
Converts a string into a "Long", if invalid returns 0
-
ToEnumerable
Convert an type T to IEnumerable
. -
FirstCharToUpper
Contact for email:ugurdemirel@bayburt.edu.tr
-
List<T>.AreAllSame()
Simple extension method Check if all items are the same in a List.
This extension method will return true if all of the elements in the list are the same.
The original author is MSkuta
This extension method is getting from :https://stackoverflow.com/a/35839942/5483868
-
IsFilled(), IsEmpty()
IsFilled and IsEmpty provide a more natural (english language) alternative to check if the value of a string is null, empty or filled
-
GetEnumDescription
Gets the description attribute assigned to an item in an Enum.
-
Map
Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.
(like Arduino function map)
Parameters
value: the number to map.
fromLow: the lower bound of the value’s current range.
fromHigh: the upper bound of the value’s current range.
toLow: the lower bound of the value’s target range.
toHigh: the upper bound of the value’s target range.
-
AddWorkDays
This extension add "working day" to a date, where working day means from Monday to Friday.
-
WriteToFileUtf8
Write File in UTF8 from MemoryStream
-
InsertSorted
Insert an item to a sorted List
-
NullableSum
Takes an array of nullable values and sums them up. Can be easily replaced with int?
-
DataTableToList
Convert DataTable To List
-
ConvertToDateTimeNullable
ConvertToDateTimeNullable
-
Between
c# version of "Between" clause of sql query with including option
-
Cached
Cache result of IEnumerable iteration. Similar to other implemetations with two advantages: 1 - Not flawed (Dispose of IEnumerator done by compiler) 2- Simplier
-
Chainable List.Add / typesafe
Allows you to chain .Add method
-
IsNullOrEmpty
Check either IList object is null or empty.
-
IsMatchRegex
Check if a string is match with given regular expression pattern
-
IfNullElse
Check if string is null or white spaces and return null alternate value
-
ApplicationBuilderExtensions
.Net Core use package.json files
-
IsNullThen
Replaces NULL with the specified replacement value.
-
ToArray
Converting XmlDocument to byte array and vice versa
-
CheckSheba
چک کردن شماره شبا وارد شده جهت درست بودن فرمت و الگوریتم آن
-
ThrowIf
Just throw if you can
-
CamelCaseToHumanCase
Turn any string formed with camel case into a human cased string.
-
SplitCamelCase
Split any string using camel case pattern.
-
RemoveTicks
Legible way to remove ticks from a datetime. Use instead Add negative days
-
WherePrevious
Compare Through a predicate every element of a list with the previous one
-
RemoveTraillingZeros
Remove trailling zeros from a decimal value
-
Like SQL on C#
An C# extension method based on "LIKE" operator of T-SQL.
-
WriteToXML
Serializes objects into and from XML documents
-
Append() and Prepend()
Append() adds a value to the end of the sequence. Prepend() adds a value to the beginning of the sequence. This is usefull if you are not using .NET Core or .NET Framework 4.7.