Geeks With Blogs
Jim Lahman's Blog Fortitude|Endurance|Faith|Teamwork

I use structures to group data, such as messages or data records. I also use structures to pass groups of data between functions so that I don't have a long parameter list.

Ususually, structures are used within the same class, but I use them to between classes. To allow more than one class to use the structure, I encapsulate the structure(s) within another class that is used by all the classes that use the structure.

In this example, I pass a structure from a function in one class to another function in another class as a parameter.

First, we define the structure in its own class.

   1:  using System;
   2:   
   3:  namespace TestStruct
   4:  {
   5:      public class TestStruct
   6:      {
   7:          public struct strTest
   8:         {
   9:             public int iA;
  10:             public int iB;
  11:             public int iC;
  12:             public int iD;
  13:             public bool boA;
  14:             public bool boB;
  15:         }
  16:      }
  17:  }

The first class that uses the structure which sets the data values and passes the structure to another class' function:

   1:  using System;
   2:  using TestStruct;
   3:  using TestClass;
   4:   
   5:  static void UpdateL1TableWorker()
   6:  {
   7:       strTest tS = new strTest();
   8:       testClass tC = new testClass();
   9:   
  10:       int i = 1;
  11:       int j = 2;
  12:       tS.iA = 100;
  13:       tS.iB = 200;
  14:       tS.iC = 300;
  15:       tS.iD = 400;
  16:       tS.boA = (i == 1 ? true : false);
  17:       tS.boB = (j > 3 ? true : false);
  18:       tC.useStruct(ts);
  19:  }

This class uses the structure's values:

   1:  using System;
   2:  using TestStruct;
   3:   
   4:  public void useStruct(strTest tS)
   5:  {
   6:       Console.WriteLine("iA: {0}  iB: {1}  iC: {2}  iD: {3}", tS.iA, tS.iB, tS.iC, tS.iD)
   7:  }
Posted on Monday, September 6, 2010 3:59 PM | Back to top


Comments on this post: Using C# structs between classes

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Jim Lahman | Powered by: GeeksWithBlogs.net