Solved

public variable. c#

Posted on 2014-10-02
6
150 Views
Last Modified: 2014-10-02
The good solution from it_siege (http://www.experts-exchange.com/Programming/Languages/.NET/Q_28530111.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

0
Comment
Question by:Mike Eghtebas
  • 2
  • 2
  • 2
6 Comments
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 100 total points
ID: 40357706
It should be exceedingly rare that you ever expose a variable (a.k.a. a field) publicly. Best practice is to create a public property that exposes the variable.

What is the goal here?
0
 
LVL 33

Accepted Solution

by:
it_saige earned 400 total points
ID: 40357709
To do it using a public variable (which is generally frowned upon) would take a couple of modifications (depended upon the way you wanted to do it -

1.  Using an instance variable passed as an argument:
namespace CodeSampleCS
{
    public partial class frmCS01 : Form
    {
        private Program caller = null;
        public frmCS01(Program argument)
        {
            if (argument != null)
                caller = argument;

            InitializeComponent();
        }

        private void frmCS01_Load(object sender, EventArgs e)
        {
            MessageBox.Show(string.Format("msg form{0}", !string.IsNullOrEmpty(caller.cnString) ? string.Format(" - {0}", caller.cnString) : "")); 
        }
    }
}
--------------------------------------------
namespace CodeSampleCS
{
    class Program
    {
        public 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(this));
            MessageBox.Show("msg 2" + cnString);
        }
    }
}

Open in new window


2.  Implement a globals class:
namespace CodeSampleCS
{
    public class Globals
    {
        private static string cnString = string.Empty;
        public static string ConnectionString
        {
            get { return cnString; }
            set 
            {
                if (!string.IsNullOrEmpty(value) && !value.Equals(cnString))
                    cnString = value;
            }
        }
    }
}

namespace CodeSampleCS
{
    public partial class frmCS01 : Form
    {
        public frmCS01()
        {
            InitializeComponent();
        }

        private void frmCS01_Load(object sender, EventArgs e)
        {
            MessageBox.Show(string.Format("msg form{0}", !string.IsNullOrEmpty(Globals.ConnectionString) ? string.Format(" - {0}", Globals.ConnectionString) : "")); 
        }
    }
}
--------------------------------------------
namespace CodeSampleCS
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            XmlTextReader xmlReader = new XmlTextReader("csNorthwind.xml");
            Globals.ConnectionString = xmlReader.ReadElementString("connection");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            MessageBox.Show("msg 1" + Globals.ConnectionString);
            Application.Run(new frmCS01());
            MessageBox.Show("msg 2" + Globals.ConnectionString);
        }
    }
}

Open in new window


-saige-
0
 
LVL 33

Author Comment

by:Mike Eghtebas
ID: 40357764
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
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40357774
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.
0
 
LVL 33

Expert Comment

by:it_saige
ID: 40357780
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-
0
 
LVL 33

Author Comment

by:Mike Eghtebas
ID: 40357823
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question