Lajos Arpad Lajos Arpad - 3 months ago 9
C# Question

Why does vb.net allow class names to be parameter names?

I have seen a

Sub
which looked like this:

Private Sub DoSomething(ByRef PlaceHolder As PlaceHolder)
'Do something with the PlaceHolder object
End Sub


I wonder why is this allowed. I can name a few languages where this is not allowed. I would like to be able to have methods with the very same return, parameters and names if one of them is
Shared
, the other is instance-level.

For example, let us suppose there is a
Class
named
Bird
and there is an object like this

Dim bird = New Bird("Duck Doggers")


bird.fly()
would make sure that Duck Doggers flies, however,
Bird.fly()
would make all the birds fly, if, for instance an
IEnumerable
would be updated upon each constructor run of
Bird
and
Bird.fly
would iterate that
IEnumerable
and call
fly
for each item. As far as I can see, this is impossible in vb.net, since fly would be either
Shared
or instance-level. Is there any possible problem (besides unclarity) if a parameter name is the very same as the
Class
name whose instance is the said parameter?

I do not have C# in front of me, but I wonder whether naming of a parameter exactly as a
Class
is possible there.

Answer

This is a very common naming pattern to the majority of VB developers. Much of it stems from VB being case-insensitive. Without being allowed to name variables this way, either the variable, or the class name would have to be renamed "creatively" to avoid conflicts, that just leads to things like Hungarian Notation, or other strange naming patterns. While it may look odd to someone who isn't used to it, it quickly becomes 2nd nature to a VB developer. Calling a shared member on an instance variable just "passes though" to the shared member, as in the following example.

Public Class Bird
    public Shared sub Fly
        Debug.WriteLine("Fly called from Shared")
    End sub

    public sub Quack
        Debug.WriteLine("Quack called from Instance")
    End sub

End Class

Public Class Main
    public sub Test(bird As Bird)
        bird.Fly()
        Bird.Fly()

        bird.Quack()
        Bird.Quack()
    End sub
End Class

Calling Test results in the following output.

Fly called from Shared

Fly called from Shared

Quack called from Instance

Quack called from Instance