Here's an example of what I'm talking about...
Public Class Sample1
Public Shared Function MyValue() As Integer
Return 0
End Function
Public Sub Code()
Dim ThisIsBad = Me.MyValue
Dim ThisIsGood = Sample1.MyValue
End Sub
End Class
Me.MyValue
gives a warning in VB.NET and (the equivalent code gives) an error in C#. Is there a particular reason for this? I find it more intuitive/natural to access the shared function using 'Me.MyValue' - but I avoid it to keep my warnings at 0.
Did someone else just decide 'Nah, it makes more sense to do it the other way' or is there some technical reason I don't understand?
EDIT:
Thanks everyone. I was thinking of it wrong, more like a 'sub class' in OOP. Even if something is declared in the base class, you access it through the instance you have. But that relationship is not the same with shared or static.
Static members by definition are declared at the class level, not the instance level, and so accessing a static member using this
(or me
in VB) doesn't really feel right (and isn't right in C#)
Saying this.something
(or me.something
) implies you are accessing "something" that's particular to that specific instance, while, again, static members are shared throughout all instances of that class.
It's misleading for the reader of your code.
Code should be written to be read and understood by another programmer, wo doesn't know every detail of the project. Accessing a static variable through an instance makes it look like an instance member - you'd have to check the declaration to see you are mistaken.
That "other programmer" might as well be you after half a year.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With