C
C#2mo ago
tommy

why do we declare overloaded operators as `static` methods?

i have been looking for a simple answer that i can understand because i am beginner.
16 Replies
✿ Scarlet ✿
✿ Scarlet ✿2mo ago
Just a design decision
canton7
canton72mo ago
If you have two different types, it lets the compiler pick a suitable method to call from either type.
MODiX
MODiX2mo ago
canton7
REPL Result: Success
int i = new D() + new C();

public class C
{
public static int operator +(D d, C c) => 1;
}

public class D { }
int i = new D() + new C();

public class C
{
public static int operator +(D d, C c) => 1;
}

public class D { }
Compile: 340.389ms | Execution: 29.090ms | React with ❌ to remove this embed.
canton7
canton72mo ago
If they were instance methods, you might have the problem where new D() + new C() calls D.Add(C), but new C() + new D() calls C.Add(D), and those two methods on different types might do different things (particularly when inheritance starts getting involved). By having them be static, the compiler gets to look at all of the applicable methods across all types which are involved, and pick the most suitable
arion
arion2mo ago
I'm still waiting for the day we make static non-mandatory if the underlying class is static. (Like the unsafe keyword)
canton7
canton72mo ago
Eh, then you have to scroll all the way to the top of the class to see whether a method is static
arion
arion2mo ago
If a class is static, every method will be static. It beats writing static 100x. (Unless thats your thing of course) Same for unsafe. If the entire class is unsafe, each method is unsafe. Unsafe on the class level also disables async for methods in that respective class (until .NET 9) Rider has a nice thing of pinning the current class to the viewport
canton7
canton72mo ago
... but you still have to scroll up to the top of the class to see whether a method is static. It's more "spooky action at a distance", which experience tells us is best avoided
arion
arion2mo ago
Tell that to the team who made this functionality for the unsafe keyword already.
canton7
canton72mo ago
Just because you've made a mistake once, doesn't mean you need to make it again 😛
arion
arion2mo ago
:Dead: I... can't argue with that lol
blueberriesiftheywerecats
Oftop but what theme are you using?
arion
arion2mo ago
JetBrains Marketplace
Nightfall Theme - IntelliJ IDEs Plugin | Marketplace
A dark, clean, simple and elegant theme for JetBrains IDE.
Want results from more Discord servers?
Add your server