Mike Eghtebas
asked on
public variable. c#
The good solution from it_siege (https://www.experts-exchange.com/questions/28530111/variable-scope-c.html) uses arguments to pass cnString variable.
Question: Could you please revise this code to do it using a public variable?
Question: Could you please revise this code to do it using a public variable?
namespace CodeSampleCS
{
public partial class frmCS01 : Form
{
private string cnString = string.Empty;
public frmCS01(string argument)
{
if (!string.IsNullOrEmpty(argument))
{
cnString = argument;
}
InitializeComponent();
}
private void frmCS01_Load(object sender, EventArgs e)
{
MessageBox.Show(string.Format("msg form{0}", !string.IsNullOrEmpty(cnString) ? string.Format(" - {0}", cnString) : ""));
}
}
}
--------------------------------------------
namespace CodeSampleCS
{
static class Program
{
public static string cnString = "";
[STAThread]
static void Main()
{
XmlTextReader xmlReader = new XmlTextReader("csNorthwind.xml");
cnString = xmlReader.ReadElementString("connection");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MessageBox.Show("msg 1" + cnString);
Application.Run(new frmCS01(cnString));
MessageBox.Show("msg 2" + cnString);
}
}
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
With vba background, having a global variable and using everywhere has its advantages.Yes, that's typically the feeling of people who come from backgrounds where globals are prevalent. But as you program (object-oriented) more and more, and your programming becomes more advanced, you will begin to see how globals actually can do more harm that good. They especially make parallel programming difficult.
Parrallel programming and threading are two examples of why I stated
-saige-
which is generally frowned upon@kaufmed - I just now realized that your avatar is not a pirate. :D
-saige-
ASKER
Follow up question if you have a moment: https://www.experts-exchange.com/questions/28530191/connection-string-is-not-read.html
ASKER
With vba background, having a global variable and using everywhere has its advantages.
I appreciate good comments and suggestion from both and follow it accordingly.
The current question is also good to know to be used when it is appropriate but not reading connection string.
I have a follow up question as to why cnString read from the xml file is different. I will post a link shortly.
Mike