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
Just a design decision
If you have two different types, it lets the compiler pick a suitable method to call from either type.
canton7
REPL Result: Success
Compile: 340.389ms | Execution: 29.090ms | React with ❌ to remove this embed.
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 suitableI'm still waiting for the day we make
static
non-mandatory if the underlying class is static. (Like the unsafe
keyword)Eh, then you have to scroll all the way to the top of the class to see whether a method is static
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
... 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
Tell that to the team who made this functionality for the
unsafe
keyword already.Just because you've made a mistake once, doesn't mean you need to make it again 😛
:Dead: I... can't argue with that lol
Oftop but what theme are you using?
https://plugins.jetbrains.com/plugin/16142-nightfall-theme but with custom color scheme
JetBrains Marketplace
Nightfall Theme - IntelliJ IDEs Plugin | Marketplace
A dark, clean, simple and elegant theme for JetBrains IDE.