.net - Is there such thing as a variable for my whole solution? -
seems beginner, have big solution, , problem when user in subroutine store date in variable in frmmain.vb, based in project 1. after user steps user control in project b, need have same value user stored in frmmain.vb.
could please guide me through on how possible?
forget noise how can use global variable. fact you're asking question implies you're new language , want learn right way of doing things. that's great!
but real answer little bit more complicated. truth is, global variables have fallen out of favor modern programming tasks. vb.net in particular (as many other popular languages) object-oriented language, means interact methods on individual instances of objects. object-oriented programming provides host of benefits, presents whole new set of challenges. if don't have book you're learning vb.net from, highly suggest stop , pick 1 up.
it's far easier pick habits in beginning unlearn bad habits later. , trust me, global variables bad habit , wrong way write code in vb.net. there are ways it, don't want use those. ignore them @ costs. temptation "easy" way isn't worth it.
the quick, executive summary need create public property in form's class. (remember, in vb.net, form instance of class. inherits form
class gets of base functionality free.) public property sort of global variable in allows other classes access value outside, it's preferred way of doing things in object-oriented languages. in vb.net, code public property might this:
public class myform : inherits system.windows.forms.form ' private field (variable), visible inside of class private myfavoritecolor color = color.blue ' public property expose favorite color other classes public property favoritecolor color ' returns value of private variable return myfavoritecolor end set(byval value color) ' sets private variable specified value myfavoritecolor = value end set end property ' ... rest of form code go here end class
and outside of form, might have following code:
public class secondform : inherits system.windows.forms.form public sub mymethod ' create instance of myform class dim frm myform = new myform() ' show form frm.show() ' read value of favorite color property, ' , display in message box messagebox.show(frm.favoritecolor.tostring) ' ... whatever else want form ' close form frm.close() end sub ' ... other code second form might go here end class
notice how able read value of variable stored inside of frm
object (an instance of myform
class) inside of different class? way, avoid storing global state information. instead, you've kept variables (and information contain) enclosed within particular classes apply to. , didn't have reach in , touch other class object's private parts, because exposed them using public property. that's right way this. mentioned above, make sure you're learning book teaches object-oriented programming along other basics. you'll regret doing other way.
Comments
Post a Comment