Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Shouldn't You Access a Shared/static Member Through An Instance Variable?

Tags:

c#

.net

vb.net

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.

like image 463
Rob P. Avatar asked Mar 03 '11 15:03

Rob P.


2 Answers

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.

like image 124
Adam Rackis Avatar answered Oct 27 '22 10:10

Adam Rackis


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.

like image 36
peterchen Avatar answered Oct 27 '22 11:10

peterchen