extension-methods

Raising C# events with an extension method - is it bad?

Deadly 提交于 2019-11-27 11:12:05
We're all familiar with the horror that is C# event declaration. To ensure thread-safety, the standard is to write something like this : public event EventHandler SomethingHappened; protected virtual void OnSomethingHappened(EventArgs e) { var handler = SomethingHappened; if (handler != null) handler(this, e); } Recently in some other question on this board (which I can't find now), someone pointed out that extension methods could be used nicely in this scenario. Here's one way to do it: static public class EventExtensions { static public void RaiseEvent(this EventHandler @event, object sender

F# extension methods in C#

折月煮酒 提交于 2019-11-27 11:07:35
If you were to define some extension methods, properties in an assembly written in F#, and then use that assembly in C#, would you see the defined extensions in C#? If so, that would be so cool. [<System.Runtime.CompilerServices.Extension>] module Methods = [<System.Runtime.CompilerServices.Extension>] let Exists(opt : string option) = match opt with | Some _ -> true | None -> false This method could be used in C# only by adding the namespace (using using) to the file where it will be used. if (p2.Description.Exists()) { ...} Here is a link to the original blogpost. Answering question in

Ambiguous call between two C# extension generic methods one where T:class and other where T:struct

╄→гoц情女王★ 提交于 2019-11-27 10:52:00
Consider two extension methods: public static T MyExtension<T>(this T o) where T:class public static T MyExtension<T>(this T o) where T:struct And a class: class MyClass() { ... } Now call the extension method on a instance of the above class: var o = new MyClass(...); o.MyExtension(); //compiler error here.. o.MyExtension<MyClass>(); //tried this as well - still compiler error.. The compiler says that calling the method is an ambiguous call when I call it on a class. I would have thought that it could determine which extension method to call, as MyClass is a class, not a struct? Jon Skeet

How to extend C# built-in types, like String?

末鹿安然 提交于 2019-11-27 10:50:01
Greetings everyone... I need to Trim a String . But I want to remove all the repeated blank spaces within the String itself, not only at the end or at the start of it. I could do it with a method like: public static string ConvertWhitespacesToSingleSpaces(string value) { value = Regex.Replace(value, @"\s+", " "); } Which I got from here . But I want this piece of code to be called within the String.Trim() itself, so I think I need to extend or overload or override the Trim method... Is there a way to do that? Thanks in advance. JoeyRobichaud Since you cannot extend string.Trim(). You could

Extension methods defined on value types cannot be used to create delegates - Why not?

梦想的初衷 提交于 2019-11-27 10:30:36
问题 Extension methods can be assigned to delegates that match their usage on an object, like this: static class FunnyExtension { public static string Double(this string str) { return str + str; } public static int Double(this int num) { return num + num; } } Func<string> aaMaker = "a".Double; Func<string, string> doubler = FunnyExtension.Double; Console.WriteLine(aaMaker()); //Prints "aa" Console.WriteLine(doubler("b")); //Prints "bb" If the type they're extending is a value type, it won't work:

What is the best or most interesting use of Extension Methods you've seen? [closed]

别说谁变了你拦得住时间么 提交于 2019-11-27 09:57:31
I'm starting to really love extension methods... I was wondering if anyone her has stumbled upon one that really blew their mind, or just found clever. An example I wrote today: Edited due to other users' comments: public static IEnumerable<int> To(this int fromNumber, int toNumber) { while (fromNumber < toNumber) { yield return fromNumber; fromNumber++; } } This allows a for loop to be written as a foreach loop: foreach (int x in 0.To(16)) { Console.WriteLine(Math.Pow(2, x).ToString()); } I can't wait to see other examples! Enjoy! The full solution is too large to put here, but I wrote a

ASP.NET repeater alternate row highlighting without full blown <alternatingitemtemplate/>

我的未来我决定 提交于 2019-11-27 09:56:57
问题 I'm trying to accomplish simply adding a css class to a div on alternate rows in my <itemtemplate/> without going to the overhead of including a full blown <alternatingitemtemplate/> which will force me to keep a lot of markup in sync in the future. I've seen a solution such as http://blog.net-tutorials.com/2009/04/02/how-to-alternate-row-color-with-the-aspnet-repeater-control/ which I'm tempted to use but this still doesn't "smell" right to me. Has anyone else got a more maintainable and

Is calling an extension method on a “null” reference (i.e. event with no subscribers) evil?

半腔热情 提交于 2019-11-27 09:24:10
问题 Evil or not evil? public static void Raise(this EventHandler handler, object sender, EventArgs args) { if (handler != null) { handler(sender, args); } } // Usage: MyButtonClicked.Raise(this, EventArgs.Empty); // This works too! Evil? EventHandler handler = null; handler.Raise(this, EVentArgs.Empty); Note that due to the nature of extension methods, MyButtonClicked.Raise will not throw a NullReferenceException if MyButtonClicked is null. (E.g. there are no listeners to MyButtonClicked event).

What causes “extension methods cannot be dynamically dispatched” here?

自闭症网瘾萝莉.ら 提交于 2019-11-27 09:23:56
Compile Error 'System.Data.SqlClient.SqlConnection' has no applicable method named 'Query' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. Now, I know how to work around the problem, but I'm trying to get a better understanding of the error itself. I have class that I'm building to leverage Dapper. In the end I'm going to provide some more custom functionality to make our type of data access a lot more streamlined. In particular

The operation cannot be completed because the DbContext has been disposed error

家住魔仙堡 提交于 2019-11-27 08:49:24
I'm new to EF and I'm trying to use an extension method which converts from my Database type User to my info class UserInfo . I'm using database first if that makes a difference? My code below gives the error The operation cannot be completed because the DbContext has been disposed. try { IQueryable<User> users; using (var dataContext = new dataContext()) { users = dataContext.Users .Where(x => x.AccountID == accountId && x.IsAdmin == false); if(users.Any() == false) { return null; } } return users.Select(x => x.ToInfo()).ToList(); // this line is the problem } catch (Exception ex) { //... } I