extension-methods

Extension method call does not compile, but static method call to same code does compile

落爺英雄遲暮 提交于 2019-12-05 08:27:31
There is library A calling library B using a C# extension method. I got a weird error from the C# compiler: The type 'System.Windows.Forms.Control' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Windows.Forms, Version=4.0.0.0 None of the libraries A or B are dependent on System.Windows.Forms.Control , nor has any dependency of A a dependency on System.Windows.Forms.Control . System.Windows.Forms.Control is only referenced from another project in the same solution. The weird thing is that if I change the call syntax to static method, it compiles

ForEach Extension Method for ListItemCollection

不打扰是莪最后的温柔 提交于 2019-12-05 08:20:39
I implemented an ExtensionMethod which basically works as ForEach-Loop, my Implementation looks like this: public static void ForEach(this ListItemCollection collection, Action<ListItem> act ) { foreach (ListItem item in collection) act(item); } However, I'd like the method to stop looping after the first time a specific condition is met. Here's how I currently use it: ddlProcesses.Items.ForEach(item => item.Selected = item.Value == Request["Process"]?true:false); The Problem with this is that there can only be one item inside the DropDownList which matches this requirement, but the loop is

How can I return <TEnumerable, T> : where TEnumerable:IEnumerable<T>

白昼怎懂夜的黑 提交于 2019-12-05 07:28:24
Goal: Generic enumerated type to be the same type when returned. Note: This works when the types are entered but I don't understand why they can't be inferred. List<T> then return List<T> IOrderedEnumerable<T> then return IOrderedEnumerable<T> ETC Current method (works only if all types are entered) public static TEnumerable WithEach<TEnumerable, T>(this TEnumerable items, Action<T> action) where TEnumerable : IEnumerable<T> { foreach (var item in items) action.Invoke(item); return items; } Example Only var list = new List<int>(); //TODO: Mock random values list.WithEach(x => Console.WriteLine

How can additional data be associated with existing objects using extension methods?

依然范特西╮ 提交于 2019-12-05 06:41:57
Since .NET Framework 3.5, developers have been able to add extension methods callable from instances of any object type. Extension properties have not been implemented in C#, however. Unlike extension methods, extension properties would involve storing some extra state information for individual objects. However, even for extension methods, it would be highly useful in some programming scenarios to be able to access after-added/extension information for the objects on which those extension methods are called. Here is the original question: How can one add extension properties, or otherwise set

Generic Enum to SelectList extension method

大憨熊 提交于 2019-12-05 06:17:13
I need to create a SelectList from any Enum in my project. I have the code below which I create a select list from a specific enum, but I'd like to make an extension method for ANY enum. This example retrieves the value of the DescriptionAttribute on each Enum value var list = new SelectList( Enum.GetValues(typeof(eChargeType)) .Cast<eChargeType>() .Select(n => new { id = (int)n, label = n.ToString() }), "id", "label", charge.type_id); Referencing this post , how do I proceed? public static void ToSelectList(this Enum e) { // code here } What I think you are struggling with, is the retrieval

Why can't I implicitly cast a Delegate with Extension methods?

倖福魔咒の 提交于 2019-12-05 05:53:40
I'm trying to figure out a way to automatically cast something to an Action or Func and the best I can come up with is something like this: [TestFixture] public class ExecutionTest { public void BadMethod() { throw new Exception("Something bad happened"); } [Test] public void TestBadMethod() { // Want this, but it won't work!! // BadMethod.Execute().IgnoreExceptions(); // Ick ((Action)BadMethod).Exec().IgnoreExceptions(); // Still ick ((Action)BadMethod).IgnoreExceptions(); // Do not want ExtensionMethods.Exec(BadMethod).IgnoreExceptions(); // Better but still meh this.Exec(BadMethod)

Extending F# List Module

♀尐吖头ヾ 提交于 2019-12-05 05:42:29
I've been adding a few handy methods to some of the F# modules such as List. type Microsoft.FSharp.Collections.FSharpList<'a> with //' static member iterWhile (f:'a -> bool) (ls:'a list) = let rec iterLoop f ls = match ls with | head :: tail -> if f head then iterLoop f tail | _ -> () iterLoop f ls and i'm wondering if it's possible to add mutation? I know List is immutable so how about adding a mutable method to Ref of type List. Something like this. type Ref<'a when 'a :> Microsoft.FSharp.Collections.FSharpList<'a> > with //' member this.AppendMutate element = this := element :: !this or is

Design choice: Do I want extension methods to throw exceptions on null? [duplicate]

橙三吉。 提交于 2019-12-05 05:40:10
This question already has answers here : Closed 8 years ago . Possible Duplicate: C#: Best practice for validating “this” argument in extension methods I'm ambivalent about a design choice, and would like to hear the opinions of the SO community. The example I bring up here is just one possible case where this design choice has to be made - in reality, there might be many more cases. Answers are welcome both to this specific case and to a more general approach, and guidelines on how to make the decision in a specific case are also appreciated. Basically, I want to know how to think about this:

Error message “Operator '.' cannot be applied to operand of type 'lambda expression'” when converting a method to Extension Method?

余生长醉 提交于 2019-12-05 03:54:11
I have a method which i want to convert to Extension Method public static string GetMemberName<T>(Expression<Func<T>> item) { return ((MemberExpression)item.Body).Member.Name; } and calling it like string str = myclass.GetMemberName(() => new Foo().Bar); so it evaluates to str = "Bar"; // It gives the Member name and not its value Now when i try to convert this to extension method by this public static string GetMemberName<T>(this Expression<Func<T>> item) { return ((MemberExpression)item.Body).Member.Name; } and call it like string str = (() => new Foo().Bar).GetMemberName(); Error says

Extension method and Explicit casting

六月ゝ 毕业季﹏ 提交于 2019-12-05 03:23:54
I'm using class from some assembly(source code is not available), so it is not possible to change their's code I need to add extension method for explicit cast operator, is there any way to achieve that? (I have tried to add as regular extension method, but without success) public static explicit operator MembershipUser(this MembershipUser membership, User user) { return new MembershipUser("SimplyMembershipProvider", user.UserName, user.UserId, user.Email, null, null, user.IsApproved, user.IsLocked, user.CreateDate, user.LastLoginDate, user.LastActivityDate, user.CreateDate, DateTime.MinValue)