Link to home
Start Free TrialLog in
Avatar of Mike Eghtebas
Mike EghtebasFlag for United States of America

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?

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);
        }
    }
}

Open in new window

SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mike Eghtebas

ASKER

kaufmed,

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
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
which is generally frowned upon
@kaufmed - I just now realized that your avatar is not a pirate.  :D

-saige-