开发者

How can i call a variable in my public class on vb.net?

开发者 https://www.devze.com 2023-03-30 09:49 出处:网络
I have this public class Public Class commonSettings Dim etcString As String = \"some string\" En开发者_开发知识库d Class

I have this public class

    Public Class commonSettings
        Dim etcString As String = "some string"
    En开发者_开发知识库d Class

How can i call etcString and use it entirely on my code?


Make it accessible through a public property

Public Class commonSettings
    Dim etcString As String = "some string"
    Public Property mETCString(ByVal value as String) As String
         Get
              return etcString
         End Get
         Set(value as String)
              etcString = value
         End Set
    End Property
End Class

OR if using VB 10 (VS 2010) - use an Auto-Implemented Property

Public Class commonSettings
    Public Property etcString As String = "some string"
End Class

Or make the variable directly accesible

Public Class commonSettings
    Public etcString As String = "some string"
End Class

However as Konrad mentioned creating a public variable isn't the best idea. The reasonings behind this are as follows:

  • If you change the internal implementation you are potentially breaking external dependencies.
  • You can't use DataBinding on a variable
  • Variables are seen as more of an implementation level item whereas properties define more of the interface to an object.


Use the Public modifier.

http://msdn.microsoft.com/en-us/library/ms973875.aspx#methodscope_topic3

If you want to be able to access it without an instance, use the Shared modifier as well.

Edit: Code sample

Public Class commonSettings
    Public Shared etcString As String = "some string"
End Class


In addition to msarchet's answer (which is probably the correct answer for this question "How do I make a member less private"), if you are looking for the variable to be stateless, (meaning you don't have to have an instance of the surrounding class) and you don't want it to be a shared member (so you won't have to write classname.membername), you may be looking for a Module.

You make a module like this:

Module GlobalVars
    Public etcString as String = "Some String"
End Module

Then call it from anywhere in the program simply by saying

etcString = "New String"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号