Static extension methods [duplicate]

In short, no, you can’t. Long answer, extension methods are just syntactic sugar. IE: If you have an extension method on string let’s say: public static string SomeStringExtension(this string s) { //whatever.. } When you then call it: myString.SomeStringExtension(); The compiler just turns it into: ExtensionClass.SomeStringExtension(myString); So as you can see, there’s no way to … Read more

Why is the ‘this’ keyword required to call an extension method from within the extended class

A couple points: First off, the proposed feature (implicit “this.” on an extension method call) is unnecessary. Extension methods were necessary for LINQ query comprehensions to work the way we wanted; the receiver is always stated in the query so it is not necessary to support implicit this to make LINQ work. Second, the feature … Read more

Is it appropriate to extend Control to provide consistently safe Invoke/BeginInvoke functionality?

You should create Begin and End extension methods as well. And if you use generics, you can make the call look a little nicer. public static class ControlExtensions { public static void InvokeEx<T>(this T @this, Action<T> action) where T : Control { if (@this.InvokeRequired) { @this.Invoke(action, new object[] { @this }); } else { if … Read more

How do extension methods work?

First, here’s a very quick tutorial on extensions for those learning c#/Unity for anyone googling here: Make a new text file HandyExtensions.cs like this … (note that somewhat confusingly, you can use any name at all for the class which “holds” your extensions – the actual name of the class is never used at all, … Read more

In C#, what happens when you call an extension method on a null object?

That will work fine (no exception). Extension methods don’t use virtual calls (i.e. it uses the “call” il instruction, not “callvirt”) so there is no null check unless you write it yourself in the extension method. This is actually useful in a few cases: public static bool IsNullOrEmpty(this string value) { return string.IsNullOrEmpty(value); } public … Read more

tech