FAQ Database Discussion Community


How to write an extension method to return the type being used?

c#,.net,.net-4.5,extension-methods
I have an extension method that allows a user to turn off lazy loading. public static IBaseEntityService<TEntity, TPrimaryKey> EnableLazyLoading<TEntity, TPrimaryKey>( this IBaseEntityService<TEntity, TPrimaryKey> baseService, bool enabled) where TEntity :Entity<TPrimaryKey> where TPrimaryKey : struct { baseService.UnitOfWork.EnableLazyLoading(enabled); baseService.UnitOfWork.EnableProxyCreation(enabled); var type = baseService.GetType().; return (type)baseService; } Here is a sample of the base...

DependencyProperty in DataTemplate not working

c#,wpf,extension-methods,dependency-properties
I have an issue which is driving me crazy. I have a dependecyproperty, Uid, in an extensionclass. I this to set a static "language" string (tools:TranslateExtension.Uid="MAINWINDOW_ARTICLES"). I then use the Text="{tools:Translate}" to trigger a lookup for the set language. This will call ProvideValue method which will set up a binding....

How do I cleanly write a method that takes any type of Enum to return out all of its enumerations?

c#,generics,enums,extension-methods
I have written two methods that take a generic enum and return all of its enumerations. The problem is that neither are best practise. So, I suspect that are could be another way that may take a different approach. Anyway, here are the two methods: One public static List<T> GetTypedEnumItems<T>(...

How do I tell linq2db how to translate a given expression, ie Split(char) into SQL when it does not know how to do so?

c#,linq,linq-to-sql,extension-methods,linq2db
I am using linq2db and while it works well enough for most CRUD operations I have encountered many expressions that it just cannot translate into SQL. It has gotten to the point where unless I know in advance exactly what kinds of expressions will be involved and have successfully invoked...

Is ToTitleCase supposed to capitalize letters after the apostrophe?

vb.net,asp.net-mvc-5,extension-methods
I have searched but not found an answer. I have this as an extension method: <Extension()> _ Public Function ChangeCase(ByVal source As String) As String Return New System.Globalization.CultureInfo("en-US").TextInfo.ToTitleCase(source) End Function But it is capitalizing the letter after the apostrophe. Is it supposed to do that? For example I'll becomes I'Ll....

Extension method priority

c#,extension-methods
I read from https://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx that extension methods with same name and signature as existing ones on the base type are never called, but what about "overriding" an extension-method itself: using System; using System.Linq; using System.Collections.Generic; namespace ConsoleApplication1 { public class Program { public static void Main(string[] args) { var query...

Adding new object property dynamically from extension method

c#,.net,extension-methods
Here is my scenario... I want to have some base class and have some set of extension methods to this class that will be hosted probably in different assemblies. Depending on what assemblies added to the project, different properties should be calculated and stored inside. I have some base class...

How to Make a Custom Extension for Reactive Extensions

c#,.net,extension-methods,system.reactive
It is not hard to find an example of how to make a custom LINQ extension method. But I can't find an example of how to make a custom Rx extension method. Can someone point me to a resource or post an example? I'm using the latest (ver 2.2.5). I'm...

c#: Accessing object properties in Extension Methods

c#,extension-methods
I'm currently writing a c# Rummikub game. I have an object named Card that has Value and Color properties. Also, inside Player's Class, I have a list of cards (player's hand). In the Player class, I wrote some methods that get only the player's hand as parameter. stuff like: //...

Creating a table method on a user defined type (like like 'nodes' on the XML data type)

extension-methods,sqlclr
I've created working CLR based user defined table functions as well as user defined types. What I want now is a method on a CLR-UDT that returns a table. Similar to the 'nodes' method on the XML data type. The TableDefinition and FillRowMethodName properties of the SqlMethod decoration seem to...

Extension method for precisely two different types

c#,extension-methods
I'm using the code below. It's designed for a certain type to limit it's popup-ness in intellisense etc. public static Generic Get<Generic>(this Entity input) { return (Generic)input; } Now I'd like to use the same Get method for another type (or, to be fully covered, a few another types but...

C# Make sure that interface implementation inherits from a particular base class

c#,inheritance,interface,extension-methods
I have an interface public interface IInputReciever { void OnRecieveInput(InputInfo Info); } and an interface extension class public static class IInputRecieverExtensions { public static void SubscribeToInput(this IInputReciever Reciever) { //Use member of X } public static void UnsubscribeFromInput(this IInputReciever Reciever) { //Use member of X } } Let's say I...

Why does this extension method not initialize the returned object?

c#,generics,extension-methods
I wrote a generic Extension helper method to initialize some parameters of a SoapHeader, however it is not updating the returned object. What am I missing? using System.Web.Services.Protocols; public class Header: SoapHeader {} public class WS { public Header securityHeader { get; set; } } public static class SecurityHeaderExtensions {...

Can I implement an 'conversion' from string to boolean in C#?

c#,.net,type-conversion,extension-methods,implicit-conversion
There's any way to implement a implicit conversion from 'string' to 'boolean' using C#? E.g. I have the string str with value 'Y' and when I try convert to boolean it must returns me 'true'....

C# Cannot find extension method for char struct

c#,extension-methods
Basically, I have this extension method written up: public static class Extensions { public static bool IsMaths(this Char it) { if (char.IsDigit(it) || char.IsControl(it)) { return true; } foreach (char each in new char[] { '-', '+', '(', ')', '/', '*', '%', '^', '.' }) { if (each.Equals(it)) { return...

Why does this filter work on a List but not on an IQueryable?

c#,linq,extension-methods
I need to create an extension method that will filter collection List<TSource> according to a list of validation rules List<<IRule>, bool>. But I get an error VisitSubQueryExpression method is not implemented and I don't see/can not find what is the problem cause. This is my extension method: public static List<TSource>...

Why does not work the use of an extension method in the same extension method?

vb.net,reflection,extension-methods,dynamic-programming,generic-programming
I got an extension method that gives me the value of every property in an instance. For scalar values works it fine. But for Collections there is a problem. This is my code: <Extension()> Public Function ToXml(Of T)(ByVal source As T) As XmlDocument Dim oXmlDocument As New XmlDocument oXmlDocument.AppendChild(oXmlDocument.CreateXmlDeclaration("1.0", "utf-8",...

Allowing nulls on a record type F#

mongodb,generics,f#,extension-methods
I'm trying to make a type extension for MongoDB C# Driver that will return an option type instead of null when trying to execute a query that yields 0 results. I've run into a few issues on the way, but right now there is just one thing in the way....

Why doesn't this base type extension work?

swift,generics,extension-methods
Trying to play with extensions, but am having issues getting the following to work: let value = -13 abs(value) extension Int { var abs:Int { return abs(self) // -> Cannot invoke 'abs' with an argument list of type '(Int)' } } value.abs The compile error is weird, because it demonstrably...

How to resolve dependency in static class with Unity?

c#,unity,extension-methods
I have the following extension method, which exists (naturally) in a static class. public static class MyExtensions { [Dependency] private static IMyDataContext _myDataContext { get; set; } public static void MyExtensionMethod(this MyType myType) { // do stuff _myDataContext.DoAwesomeThing(); } } the _myDataContext object is null. Normally I'd use the UnityContainer...

Extension Methods and Duck Typing

f#,extension-methods,duck-typing
Why do I get an error when trying to call transform on an string? type Truck = Truck type Car = Car type Vehicle<'a> = | TruckWrapper of Truck * 'a | CarWrapper of Car * 'a type Truck with member this.transform (x) = TruckWrapper(this, x) type Car with member...

Overridden Extension Method Requires Assembly Reference [duplicate]

c#,.net,generics,.net-4.5,extension-methods
This question already has an answer here: The type is defined in an assembly that is not referenced, how to find the cause? 5 answers This seems strange unless I am missing something... public static string ToDomainSolarSystemCelestial(this TypeMapper<string> m) { // Does not reference any other assemblies - straight...

How do you add a description to you enum values in C# to use with a dropdown list in ASP.NET MVC? [duplicate]

c#,asp.net-mvc-4,enums,extension-methods
This question already has an answer here: How do you create a dropdownlist from an enum in ASP.NET MVC? 31 answers If I would like to use my enums for dropdown lists in my ASP.NET MVC view so that I can have either the enum value or enum name...

Extension methods with base and sub-classes

c#,inheritance,reflection,extension-methods
UPDATE Requesting to re-open because the other SO answers don't have a solution, but one of the comments to the question has a solution I want to accept as it works for the scenario. Original Question I am having trouble writing extension methods with non-abstract base classes and sub-classes that...

Generic type vs Extension method

c#,.net,oop,generics,extension-methods
I need to make a comparison between two techniques : Use of generic type and extend type. I don't mean a general comparison, I mean in this specific case when I need to add some features to a class named ClassA Using a generic type use a generic type (...

Can Extension-Methods overwrite instance methods? [duplicate]

c#,.net,extension-methods
This question already has an answer here: Is there any way in C# to override a class method with an extension method? 3 answers Is it possible to overwrite instance methods by an extension-methods? For example, I have an assembly (compiled, without sources) and I want to rewrite some...

How to cast generic parameter to generic interface?

c#,generics,casting,extension-methods
I want to have an extension method to print all contents of IEnumerable< X > public static IEnumerable<T> log_elements<T>(this IEnumerable<T> collection, bool recursive = true) { Form1.log("["); foreach (T i in collection) if(recursive&&(i.GetType().GetGenericTypeDefinition()==typeof(IEnumerable<>))) (IEnumerable<>)i.log_elements();//This doesn't work else Form1.log(i); Form1.log("]"); return collection; } If it contains IEnumerable< Y >, the method...

How to do a “Select” in Linq when there is no result

c#,linq,extension-methods
Lets say i have a list with 3 elements: List<int> a = new List<int>{ 1, 2, 3}; a.Select(myFunction); The second line runs "myFunction" for each element in the list. Select expects a return type. Is there an extension method similar to "select" that does not return anything? i.e. i can...

Consume Extension method in non-static class

c#,.net,extension-methods
All of the examples for extension methods that I have seen consume the extension method in a class like: class Program { static void Main() { ...Call extension method here } } These seem to work because the consuming class is static. Is there a way to consume an extension...

extention method with type specific List

c#,fluent-nhibernate,extension-methods
I want to create an extention method to bind a List, but getting this error. menuItem.Children.Bind(); public static class Extensions { public static void Bind(this IList list) { //some stuff } } class MenuItemMap : Mapper<MenuItem> { public MenuItemMap() { Id(x => x.MenuItemId); Map(x => x.Text); HasMany(x => x.Children).KeyColumn("ParentId");...

Weird extention method behaviour in LINQ query

c#,linq,enums,extension-methods
I have a custom attribute that stores display name of an Enum item. I write an Extension method that returns of Enum custom attribute display name. I use my Extension method in a LINQ query. but the output is weird. When I call my extention method in a query that...

Is it possible to loop through an enum by type?

c#,enums,extension-methods
I am making several drop down lists from enums. For example, the length of a lunchbreak enum will add dropdown list items like this: foreach (LunchBreak type in Enum.GetValues(typeof(LunchBreak))) { items.Add(new SelectListItem() { Text = SiteUtilities.GetEnumDescription(type), Value = ((int)type).ToString() }); } Where my enum is in the form of: public...

How to add new methods to an existing type in go?

go,extension-methods
Im new to golang, I want to add a convenience util method on to gorilla/mux Route and Router types: package util import( "net/http" "github.com/0xor1/gorillaseed/src/server/lib/mux" ) func (r *mux.Route) Subroute(tpl string, h http.Handler) *mux.Route{ return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h) } func (r *mux.Router) Subroute(tpl string, h http.Handler) *mux.Route{ return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)...

Why are we unable to add non-generic extension methods to generic objects?

c#,generics,extension-methods
I finally got tired of IEnumerable not having an Add method, and decided to add my own through an extension method. My initial attempt was something along these lines: public static void Add(this IEnumerable<T> items, T item) { ... } This threw the expected compiler error about T not being...

TakeWhile() function is not working properly with Boolean value.

c#,linq,extension-methods
According to the below code snippet when true value is not matched in fruit array the result value should hold all the values of array. However the TakeWhile() function is not adding the not matched value into my result list below is the code snippet. bool[] fruits = { false,...

How to extend string to deserialize binary data

c#,extension-methods
I'm using my own extension method to serialize strings (and more data types) into a file with custom binary format (external, I cannot modify that format). My method is: public static byte[] Serialize(this string str) { if (str.Length > short.MaxValue) throw new ArgumentOutOfRangeException("str", "Max length allowed is " + short.MaxValue.ToString());...

Extension Methods vs Instance Methods vs Static Class [closed]

c#,extension-methods,poco,static-classes,instance-methods
I'm a little bit confused about the different ways to use methods to interact with objects in C#, particularly the major design differences and consequences between the following: Invoking an instance method Using a static class on a POCO Creating an extension method Example: public class MyPoint { public double...

How do I add multiple attributes to an Enum?

c#,enums,extension-methods
I have a SQL lookup-table called ClientCreditResolutionPlanActionType that I want to convert to an enum in c#. Very basic request, right? Right. My table, now enum, however, has several columns, or now, description properties that need to go with it: StatusIcon StatusText TypeText So I figured I could do ......

PHP Sibling Class Inheritance

php,extension-methods,multiple-inheritance
I'm a bit confused on whether or not this is possible. I've checked a couple of posts here on SO and they don't really explain what I'm looking for. I have 3 classes. One main class and two classes extending that main class. (see code below). Is it possible to...

Change state of List inside extension method

c#,linq,extension-methods,mutable
How do I change the state of List which is part of view model in extension method so the view model reflects this change without having to re assign the value Code: //ViewModel: //This line should modify the change internally wihtout having to reassign like // ..Selected =model.CheckBoxList.Selected.RemoveWhere(c => c.SelectedValue...

Difference between FirstOrDefault() and FirstOrDefault()?

c#,linq,extension-methods
If FirstOrDefault() does not return a value, then the return value is null, what comes back from FirstOrDefault<MyClass>() and which is best practice? What are some scenarios where it would be better to use FirstOrDefault<MyClass>() because it seems that if your call does not return anything, it is best to...

Can't omit the extension type argument when calling generic extension method with mutually constrained type parameters

c#,extension-methods,generic-type-argument
public static class Utility { public static void ShadowDeserializeFile<T, S>(this T target, FileInfo file) where T : ShadowDeserializable<S> { S shadow = SomeHelpingMethod(file); target.ShadowDeserialize(shadow); } } public interface ShadowDeserializable<S> { void ShadowDeserialize(S shadow); } With above code I expect I can call it like: var something = new SomeType(); //SomeType...

Using an extension method declared and implemented in interface

c#,.net,oop,interface,extension-methods
I try to understand the Extension method concept in c#, So I added this interface : public interface IExtension { public static int Multiple(this int a) { return a * 2; } } In my Main method public static void Main() { Console.WriteLine("Entrer un numero"); int a =int.Parse( Console.ReadLine()); a.Multiple();...

Creating an extension method to wrap types as IEnumerables

c#,generics,extension-methods,ienumerable
I wanted to create an extension method that would efficiently wrap single objects as IEnumerables. This was to avoid the cases where you end up putting a new [] {} in the middle of an expression. This is easy enough to do using the following method: public static IEnumerable<TSource> WrapAsEnumerable<TSource>(this...