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
-
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.
-
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<T>. 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<T>.
-
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