Solved

public variable. c#

Posted on 2014-10-02
6
163 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 34

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 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
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
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 34

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

Major Incident Management Communications

Major incidents and IT service outages cost companies millions. Often the solution to minimizing damage is automated communication. Find out more in our Major Incident Management Communications infographic.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

734 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