Questions tagged [extension-methods]

Methods that extend a given type, adding functionality to any instance of that type, even if the type in question is defined in a separate assembly. For example, a "Disemvowel" extension method could be written to add disemvoweling functionality to any "String" object.

Filter by
Sorted by
Tagged with
5 votes
4 answers
908 views

Naming a method that gets the next enum value or starts from the beginning if the given value is the last

I'm struggling to find a proper name for a specific method (in code named NameOfExtension), and would also like some feedback about its implementation. I am ...
user avatar
  • 153
2 votes
5 answers
157 views

Substring extension method with a method of removal

I consistently have code where I need to pull individual chunks of substrings out of a larger string; while I won't get into details, it's easy to replicate in a proof of concept: ...
user avatar
0 votes
2 answers
115 views

Extension method to get the Sunday date from current date based on weekOffset

I want to write an extension method for getting Sunday Date based on weekOffset and current date. For example if weekOffset value is 1 that means next week sunday date and if weekOffset is 2 that ...
user avatar
  • 1
3 votes
1 answer
200 views

Extending method chaining IEnumerable with Add..If

I'm trying to write an extension (method chaining) for playing around a bit. What I made work is an extension to add an item to the list (what is pretty easy): ...
user avatar
1 vote
2 answers
53 views

Use proxy for jQuery-like DOM extensions

I have cleared all my scripting from the use of JQuery, but sometimes I miss a few handy extensions. Now I'm playing with the idea to "extend" ...
user avatar
  • 577
4 votes
3 answers
142 views

DistinctCount extension method

Here I go again. I have been finding a fairly common pattern in business logic code. And that pattern looks like this: ...
user avatar
2 votes
1 answer
136 views

Pass class property as parameter to extension method

I have the following class structure: MyAttribute.cs ...
user avatar
  • 202
2 votes
1 answer
110 views

Programmatically getting the GUID of an application

Intrigued by the events chronicled here (also here and here), I saw the inherent utility in having a program-specific GUID available. The SO answers that were correct seemed a bit tightly-coupled and ...
user avatar
1 vote
0 answers
205 views

Extension method: Task<T>.CoalesceAwait

There has been ongoing concern about the question of awaiting a task that could possibly be null, as when using null-coalescing operators. Consider the following: ...
user avatar
2 votes
1 answer
614 views

Extension method for getting custom Principal Claim

I'm writing extension methods to shorten the code required to get custom Claims from an IPrincipal. I have two general forms for ...
user avatar
18 votes
6 answers
6k views

Solving Fizz Buzz using LINQ in C#

The Fizz Buzz challenge is well-known and should not need any explanations, right? I recently got a bit bored and came up with a solution for Fizz Buzz using LINQ and even asynchronous code and a lot ...
user avatar
7 votes
1 answer
331 views

String Format object extension

I wrote an extension to create a string-representation by an object: ...
user avatar
3 votes
1 answer
378 views

Dotty 0.19 (Scala 3) features: contextual abstractions

tl;dr I tried to write some as general and as feasible as possible code where entities are able to communicate with other entities of the same type or of different types, allowing for the recipient ...
user avatar
3 votes
1 answer
176 views

Removing duplicate Unicode characters

Motivation I came across an interesting question on SO: determine-if-string-has-all-unique-characters and thought about providing an extension method to enable duplicate removal given some kind of ...
user avatar
  • 13.8k
2 votes
0 answers
103 views

Convenient way to make an UIImageView ExpressibleByStringLiteral

I want to reduce boiler-plate code and write like this when developing in iOS: let imgView: UIImageView = "share_fareware_text_bg" Here is implementation code: <...
user avatar
8 votes
3 answers
6k views

LINQ Extension methods MinBy and MaxBy

LINQ Extension I present a LINQ method ArgBy that returns the item of a sequence that corresponds to the predicate specified. Two additional methods ...
user avatar
  • 13.8k
5 votes
2 answers
282 views

Generic Extension Method To Count Descendants

I've created a extension method to count every available descendant starting from a single, given key. The data is a flat list, there's is no hierarchical structure. (Well, not entirely true. There ...
user avatar
  • 196
7 votes
4 answers
4k views

LINQ for generating all possible permutations

Permutate() is supposed to generate all possible permutations of the source sequence: ...
user avatar
  • 6,123
3 votes
1 answer
142 views

LINQ for extracting N bottom items (async streams)

source.Bottom(n, x => x) should be the same as well known LINQ source.OrderBy(x => x).Take(n) but is more memory/run-time ...
user avatar
  • 6,123
6 votes
1 answer
87 views

Distinguish between different types of log items in a dictionary by their key

My logging adapter is using a dictionary for storing data that is passed from middleware to middleware. It is a one-liner: ...
user avatar
  • 43.8k
1 vote
1 answer
74 views

Insert new middleware at the "right" location

I need to have my logger middlewares (nodes of a linked-list) in the right order so that they complement each other and work as desired. Any known middleware can be inserted anytime but the first and ...
user avatar
  • 43.8k
4 votes
0 answers
109 views

Toggle any application feature ON or OFF - follow-up (v2)

This is the second version of my FeatureToggle service (see previous question). It still has the same purpose which is to help control whether a feature is ...
user avatar
  • 43.8k
17 votes
3 answers
2k views

ExactlyOne extension method

I often find in codebases something on the order of if (sprockets.Count() > 0) which is easily replaced with LINQ's ...
user avatar
1 vote
0 answers
53 views

Extensible tree header context menu

I have a Qt tree view which has a custom tree header. The tree has a so called mode, by default there are two. During each of the modes a different tree is shown. The mode switcher is presented as a ...
user avatar
7 votes
5 answers
911 views

Grouping into more groups in one iteration

I had a need to group the same dataset in several groups. So instead of repeatedly query the dataset, I made an extension that could do it once. The caveat is, that the result is materialized in ...
user avatar
5 votes
2 answers
525 views

Reducing using/foreach/using nesting with a helper extension

Problem statement There are sometimes foreach scenarios that require deep nesting due to multiple disposable objects involved that look like this: ...
user avatar
  • 43.8k
5 votes
3 answers
732 views

SkipLast of an IEnumerable<T> - Linq Extension

As my answer to this question, I came up with this solution: ...
user avatar
6 votes
3 answers
333 views

Simple object validator with a new API

Quite some time ago I have created the Simple object validator (see also self-answer). The more I used it the more I thougt its API could be better so I have heavily refactored it and would like to ...
user avatar
  • 43.8k
6 votes
2 answers
3k views

Fetch and print all properties of an object graph as string

Below I have setup an extension method that takes any object, cycles through its properties, and prints each out to a Console window in the format Name: Value. ...
user avatar
  • 467
2 votes
2 answers
257 views

Build WHERE clause for search conditions [closed]

Here is a set of classes that are used to build where clause for SQL Server and Oracle for different field types e.g. text, <...
user avatar
6 votes
1 answer
315 views

Enumerate all members and types with specific attributes

I have a use-case where I need to retrieve all members with specific attributes in the class and interface hierarchy - I usually need the first match and apply its rules to child members. The built-in ...
user avatar
  • 43.8k
1 vote
0 answers
41 views

string.To2DCharArray extension method implementation

I would like to ask a code review for the class below. I am asking this because VS showed a quite low Maintainability Index of 54 and I am wondering if it is good code. I know I could have extracted ...
user avatar
3 votes
0 answers
39 views

Configure multiple application features by common criteria

My FeatureSerivce provides only basic APIs, so it is good in dealing with single features. Like I can configure only one feauture at a time: ...
user avatar
  • 43.8k
2 votes
2 answers
80 views

Creating keys/names from interfaces to avoid strings

There are many APIs that require some kind of a string key/name. I usually try to avoid using raw strings and prefer to use ...
user avatar
  • 43.8k
-1 votes
1 answer
65 views

How to divide a large method into 2 smaller methods [closed]

I have created a method that is responsible for the creation and the saving of memes. This is a huge mistake because now I need to use 1 of those functionalities (creating) for a different purpose. I ...
user avatar
2 votes
2 answers
1k views

Formatting a price in Swift using an extension vs. a class

I have a price as a Double, which I should format it as a String. Should I use an extension instead of classical class to ...
user avatar
  • 239
1 vote
0 answers
118 views

Extension "With" for immutable types

(My code is basically a rewrite of https://github.com/ababik/Remute so much of the credit goes there) The idea is to use lambda expression to provide a general With...
user avatar
  • 111
-2 votes
3 answers
44 views

Refactorizing overloads with the same scope but different calls [closed]

Well I have 3 methods that are overloads, but in it's scope has the same scope except one method call. ...
user avatar
  • 227
5 votes
2 answers
3k views

Generic extension to transform a flat nested list to hierarchy list

I have a collection of items in my database with a ParentId property. I'm reading the categories as a flat structure and I would like to convert it to a hierarchy list by populating the ParentCategory ...
user avatar
4 votes
1 answer
97 views

Immutable type updater using a special constructor

I wanted to update some properties of my UriString but since this type is immutable, it wouldn't work. Actually, I just wanted to update the Path property but I don'...
user avatar
  • 43.8k
2 votes
1 answer
75 views

Squeezing decorators into functional extensions

When you try to use several decorators it can get ugly pretty quickly and you'll end up with: ...
user avatar
  • 43.8k
8 votes
4 answers
2k views

Custom implementation of the linq Zip operator for different length lists

Based on my answer I have my implementation of linq Zip operator which operates on different length lists, and loops shortest list. My implementation: ...
user avatar
  • 251
4 votes
1 answer
119 views

Determining if there is data left after fetching a page of data

I just faced a problem where I needed to know if extra data was present in a given collection after a Take operation took place. Specifically, this is related to ...
user avatar
  • 225
1 vote
2 answers
147 views

Converting a String to USD

I'm working on a clientside iOS app for my school that involves students purchasing things, and I wrote a String extension for formatting a ...
user avatar
  • 225
3 votes
2 answers
3k views

Writing a generic casting extension-method

I'm writing a C# extension-method that converts any object to a type. E.g. the method shall convert a string with value "y" to a ...
user avatar
1 vote
2 answers
1k views

Generic TryParse extension method for the standard value types

I often need to update properties using the out parameter of the standard TryParse methods. However, use of a property as ...
user avatar
  • 263
7 votes
2 answers
784 views

Parsing small data into tuples

I'd like to make parsing small samples of data more efficient (from the developer point of view). This means, instead of writing the parsing logic each time from scratch when I encounter something as ...
user avatar
  • 43.8k
6 votes
2 answers
4k views

Split string with adding separator to substring

I wrote my Split() extension, it's main goal is to save delimiters and add them to splitted strings. For example: I have a string ...
user avatar
5 votes
1 answer
64 views

Utilities for Various Builtins #2

This is the final iteration of an iterative review. The previous iteration can be found here: Utilities for various builtins #1 This code solves the following issue: ...
user avatar
1 vote
1 answer
45 views

Utilities for various builtins #1

This is an iterative review. The next iteration is located here: Utilities for Various Builtins #2 This code puts several builtins (And a few non-builtins) into the base classes. ...
user avatar