Viewing/Retrieving data from one C# Class to another C# Class in same project.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • muzaffaralirana
    New Member
    • Nov 2008
    • 1

    Viewing/Retrieving data from one C# Class to another C# Class in same project.

    I want to know that how I can View/Retrieve data from one C# Class(e.g. "abc.cs") in another C# Class(e.g. "def.cs") in same project ?

    I have to access the variables from one class to another class. So kindly tell me that do I need to declare those variables "public", or there will be some other solution?

    Sincerely,
    Muzaffar Ali Rana.
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    You need a reference of the object containing the data you want to be available in your calling class.

    You can pass it via either
    1.) The constructor of the calling class in which class you'd probably declare it as a class instance variable (composition)
    or
    2.) A parameter to one of the methods in your calling class.

    Comment

    • nukefusion
      Recognized Expert New Member
      • Mar 2008
      • 221

      #3
      Additionally, if the data only needs to be available to the classes in the same class library, you may want to consider exposing the variables/properties as Internal rather than public.

      Code:
              public class abc
              {
                  internal int SomeData1;
              }
      
              public class def
              {
                  private abc _abc;
      
                  /// <summary>
                  /// Method 1 - composition
                  /// </summary>
                  /// <param name="input"></param>
                  internal def(abc input)
                  {
                      _abc = input;
                  }
              }
      Code:
       
              public class abc
              {
                  internal int SomeData1;
              }
      
              public class def
              {
                  /// <summary>
                  /// Method 2 - passing as parameter in method
                  /// </summary>
                  /// <param name="input"></param>
                  internal void DoSomethingWithABC(abc input)
                  {
                      input.SomeData1 += 1;
                  }
              }

      Comment

      Working...