I`m just started learning C#, used to be a VB programmer.
In VB.NET, it is possible to access a form class method, even if this method is not declared as shared.
In the code below, I don`t get compiler errors, and calling the method Foo inside ClassFoo works ok.
Public Class Form1
Public Sub Foo()
MsgBox("Test")
End Sub
End Class
Public Class ClassFoo
Sub Foo()
Form1.Foo()
End Sub
End Class
Then, I tried to port the same code to C#, but I get an error:
“An object reference is required for non-static field and bla bla bla”.
Why I can access a method not shared in VB and can`t in C#?
This is a rather horrific feature inherited from VB6, a language that allowed this construct. It is not allowed in a pure OOP language, referencing a member of an object requires an object name, not a type name.
The VB.NET team went through some trouble to make this work in the VB.NET language. “Form1” in this statement is in fact an object reference, one that gets auto-generated by the compiler. Something that goes horribly wrong when that name is used in threads btw.
But this won’t fly in the C# language, you have to supply an object reference. You will have to re-factor the code so the ClassFoo object has that reference. Something like this:
This is probably going to cause some pain while you are learning C#. The Q&D workaround for this is to use Application.OpenForms. Avoid using it if you prefer to byte the bullet.