Readability of methods with explicit 'this' parameter #7566
Replies: 3 comments 3 replies
-
Do you have any evidence to prove that using a non-virtual instance method is any slower than a static method with |
Beta Was this translation helpful? Give feedback.
-
If For function pointer, use a static wrapper function using System;
using static System.Console;
public sealed class MyClass {
int X, Y;
public MyClass (int x, int y) { X = x; Y = y; }
void DoEqual () { WriteLine (nameof (DoEqual)); }
void DoNotEqual () { WriteLine (nameof (DoNotEqual)); }
public static void DoSomethingStatic (MyClass obj) => obj.DoSomethingInstance ();
public void DoSomethingInstance () {
if (X == Y) {
DoEqual();
} else {
DoNotEqual();
}
}
}
public static class Program {
unsafe public static void Main () {
Action<MyClass> FuncDel = MyClass.DoSomethingStatic;
delegate*<MyClass,void> FuncPtr = &MyClass.DoSomethingStatic;
MyClass mc = new MyClass (1, 2);
FuncDel (mc);
FuncPtr (mc);
MyClass.DoSomethingStatic (mc);
mc.DoSomethingInstance ();
}
} |
Beta Was this translation helpful? Give feedback.
-
This will probably not be necessary with the new proposals for extensions which are written like instance members. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
For various technical reasons (mostly performance), I have a number of static methods with a parameter that is effectively a 'this' reference. Hence, these methods are littered with references to this parameter:
public class MyClass {
public static void DoSomething(MyClass obj) {
if (obj.X == obj.Y) {
obj.DoEqual();
} else {
obj.DoNotEqual();
}
}
}
Many such methods are more complicated. The sheer number of references to 'obj' (or whatever) make the code more difficult to read and understand than it needs to be. What would make the code much cleaner and more readable is if I could write:
public class MyClass {
public static void DoSomething(using this = MyClass obj) {
if (X == Y) {
DoEqual();
} else {
DoNotEqual();
}
}
}
Functionally, the two methods are identical. It's just that the latter contains a scope resolution hint to the compiler, making the programmer's life easier. (The "using this" syntax is, of course, just a suggestion.)
It also occurs to me that, if it were feasible to allow it, extension methods might also benefit from the same feature.
Beta Was this translation helpful? Give feedback.
All reactions