Is it possible to write extension methods for Console? [duplicate]

It’s not possible, as mentioned in Matt’s answer. As a workaround you could create a static class that will wrap Console adding desired functionality. public static class ConsoleEx { public static void WriteLineRed(String message) { var oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(message); Console.ForegroundColor = oldColor; } } It’s not ideal, as you have to … Read more

How can I get an extension method to change the original object?

You have to modify the contents of the List<string> passed to the extension method, not the variable that holds the reference to the list: public static void ForceSpaceGroupsToBeTabs(this List<string> lines) { string spaceGroup = new String(‘.’, 4); for (int i = 0; i < lines.Count; i++) { lines[i] = lines[i].Replace(spaceGroup, “T”); } }

How to implement left join in JOIN Extension method

Normally left joins in LINQ are modelled with group joins, sometimes in conjunction with DefaultIfEmpty and SelectMany: var leftJoin = p.Person.Where(n => n.FirstName.Contains(“a”)) .GroupJoin(p.PersonInfo, n => n.PersonId, m => m.PersonId, (n, ms) => new { n, ms = ms.DefaultIfEmpty() }) .SelectMany(z => z.ms.Select(m => new { n = z.n, m })); That will give a … Read more

How do I use an extension method in an ASP.NET MVC View?

In View: <%@ Import Namespace=”MyProject.Extensions” %> Or in web.config (for all Views): <pages> <namespaces> <add namespace=”System.Web.Mvc” /> <add namespace=”System.Web.Mvc.Ajax” /> <add namespace=”System.Web.Mvc.Html” /> <add namespace=”System.Web.Routing” /> <add namespace=”System.Linq” /> <add namespace=”System.Collections.Generic” /> <add namespace=”MyProject.Extensions” /> </namespaces> </pages>

How to use Notification.Name extension from Swift to Objective-C?

My extension in swift file extension Notification.Name { static let purchaseDidFinish = Notification.Name(“purchaseDidFinish”) } @objc extension NSNotification { public static let purchaseDidFinish = Notification.Name.purchaseDidFinish } // OBJECTIVE-C #import YourProjectName-Swift.h [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(purchaseDidFinish) name:NSNotification.purchaseDidFinish object:nil]; // SWIFT NotificationCenter.default.addObserver(self, selector: #selector(purchaseDidFinish), name: .purchaseDidFinish, object: nil) @objc func purchaseDidFinish(notification: Notification) { print(“purchaseDidFinish”) } @leanne’s answer was super helpful

C# Extension Method for Object

In addition to another answers: there would be no performance penalty because extension methods is compiler feature. Consider following code: public static class MyExtensions { public static void MyMethod(this object) { … } } object obj = new object(); obj.MyMethod(); The call to MyMethod will be actually compiled to: MyExtensions.MyMethod(obj);