Link to home
Start Free TrialLog in
Avatar of pclarke7
pclarke7

asked on

How to reference common variables in c#

I have a class called "globals" which holds multiple classes that are use by my WCF application. So for example globals consists of up to 50 classes. Until now I have been defining classes with globals  as follows:

   public class Commands
    {
        DataSet ds = new DataSet();
        DataTable dt1=new DataTable("dt1");
        DataSet ds2 ;//= new DataSet("ds2");
        DataTable dt2; //= new DataTable("dt2");
        DataRow dr2;
        string[] delimitedList1;
        string[] delimitedList2;
        string[] delimitedList3;
        string[] delimitedList4;
        string[] delimitedList5;

        string currentDataType = null;
        string ds1XmlString = " ";
        string ds2XmlString = " ";
        string myStringValue = "";
        int cnt = 0;
        DataSet dsCopy = null;
        DataSet dsCopy2 = null;
        DataSet cltDS = null;
        DataSet dsSav1 = null;
        DataSet dsSav2 = null;
        DataSet dsSav3 = null;
        DataTable fileSchema;
        public Commands()
        {

        }

Open in new window


      globals g;

I now realize that by placing globals into class Commands that it is part of this class rather than a reference.I want to create class Commands and be able to reference variables that are available in globals without having to imbed globals as part of class commands. Appreciate if someone can explain how I can achieve this ?

regards
Pat
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi Pat;

If you make the globals class a static class, something like this
public static class globals
{
     // A string variable
	public string x { get; set; }
     ....
}

Open in new window

then to reference the x variable or any public variable can be done as follows, globals.x as in globals.x = "The Value";, or string str = globals.x;

You do not instantiate a static class it comes into existence when the program starts.
Just remember - any construct like that is available to ALL threads in your app.  There will only be one instance unless you specifically make other instances.
I agree with Fernando's answer. Also remember that in C# 6 you can now import static members of types directly into scope. So you can do something similar to this example:

using static System.Console;
class Foo
{
    static void Example()
    {
        WriteLine("Hello World");
    }
}

Open in new window


This makes it really nice to use static classes in your code. I also like to use extension methods where possible to cut down on having to repeat code for often used logic.
Avatar of pclarke7
pclarke7

ASKER

Hi Fernando, Andy & Dirk,
problem is that globals holds multiple classes all of which are instanced. Therefore I cannot declare globals as a static class. I also have two instances of globals , one for UI and one for background thread.

My reason for creating a globals class was to allow for movement of  50 classes contained within globals, easily between sources using   g.MyCommands.ReceiveMyGlob(g);  However I hadn;'t realised that globals would become part of the class Commands, which was not my intention. I am now trying to find a way of removing globals from class Commands and other Classes but still need access to the variables in each of the classes in globals. If I omit globals from the class definition then how can I perform the equivalent of g.MyCommands.ReceiveMyGlob(g).

below is an example of what I am trying to achieve without having globals as part of class SomeOtherClass.

   
 public class globals 
    {
        public TransactionService MyTransactionService;
        public UserMaster MyUser;
        public EnterpriseMaster MyEnterprise;
        public TransactionHdr MyTransHdr;
        public TransactionSeq MyTransSeq;
        etc....
  }



    public class SomeotherClass 
    {
        public string MyString;
        public int MyInt;
          etc....
       
      public void DoSomething()
        {
       if (g.MyUser.username=="XXX")   // Here I want to reference a global variable without having globals g as part of class.
       {
        // Perform some logic
       }
        }

        public void ReceiveMyGlobB(globals g)
        {
            this.g= g;
        }
  }

Open in new window


regards
Pat
I'm not sure that I totally understand the reasoning behind the globals class. Nevertheless, are you copying the code from globals into the same cs file as SomeotherClass and using it that way?

Would it not be better to create a partial class? So for example, you have two .cs files in your solution. In the first, you have the following code (as an example):

First.cs file


public partial class MyFirstPartialClass
{
    private string _wordOne;
    private string _wordTwo
    
    public MyFirstPartialClass(string wordOne, string wordTwo)
    {
        _wordOne = wordOne;
        _wordTwo = wordTwo;
    }
}

Open in new window


Second.cs file


public partial class MyFirstPartialClass
{
    public string DisplayMessage()
    {
        return $"The first word is {_wordOne} and the second word is {_wordTwo}.";
    }
}

Open in new window


In a Console Application


class DisplayMessage
{
    static void Main()
    {
        MyFirstPartialClass myClass = new MyFirstPartialClass("HELLO", "WORLD");
        string sMessage = myClass.DisplayMessage();
        Console.WriteLine(sMessage);
        Console.Readline();
    }
}

Open in new window


This allows you to use the code in First.cs and Second.cs as if they were in the same class file (because actually they are when compiled). So wherever you instantiate the one, you have access to all the methods in both files.

If the above solution isn't a suitable one, why not have a look at inheritance as a way to extend your derived classes. I'm not 100% sure of how you need to implement the logic here, but perhaps this can help?
I have a feeling you are making things (very) difficult for yourself with an overall bad design.  In another question of yours I said IMHO you want to keep 'global' variables (yeuch) in a number of small but related objects and only make them available to other objects that really need them.
Maybe I am wrong but you seem to have every possible thing that might be used somewhere else in the one class and now are having immense problems trying to work with this overlarge class.

ps.  Have a search for 'singleton class' - that is more or less what is being suggested with a static class.  Read about that sort of object and think is it what you require or is it the wrong way to go.
Hi all,
thanks for you replies. I feel as if I am not expressing myself clearly and yes it is very possible that I am dealing with bad design. So I will attempt to clarify things below:

my globals class is not a static class in the true meaning of global variables and I suppose naming it globals was not the wisest decision as it causes confusion.  globals g is my instance for globals in UI and globals gb is my instance of globals for background worker.  The only reason for the globals class is for convenience. I am using it to group together all of the classes (approx. 50) in one single instance. My reason for doing so was to be able to share the 50 classes between the various source file (.cs files) via a single statement rather than having to transfer 50 classes individually  (eg.  g.MyCommands.ReceiveMyGlob(g);  )

Approx 45 of the 50 classes contained in globals g are simple classes whilst the remaining 5 classes do all of the heavy lifting. It is these five classes that require access to the globals class (or the 45 objects ). For example MyCommands  is a class which allows the user to run a command and the command needs access to all of the classes defined within the transaction  (ie globals g).

I had this logic working ,where I could access my globals g instance within each of the 5 main classes but this was working only because I had globals defined as part of each of the 5 main classes. Whilst this worked it caused problems when cloning the classes for background worker. So I am now trying to find a better way of making my non-static classes available to these main 5 classes.I don't believe partial class will work as it seems to require just 1 class rather than allowing multiple classes to access the contents of a common class (globals).

To simplify the requirement I am trying to determine whether class X can have access to the methods and data of class Y (class Y is not a static class)  without having to define Y as part of class X.

Regards
Pat
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
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
Thanks again to all that took the time to contribute