Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

public variable. c#

Posted on 2014-10-02
6
Medium Priority
?
189 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 400 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 35

Accepted Solution

by:
it_saige earned 1600 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 34

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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 35

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 34

Author Comment

by:Mike Eghtebas
ID: 40357823
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses

972 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