Using C# structs between classes

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.

using System;

namespace TestStruct
{
    public class TestStruct
    {
        public struct strTest
       {
           public int iA;
           public int iB;
           public int iC;
           public int iD;
           public bool boA;
           public bool boB;
       }
    }
}

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

using System;
using TestStruct;
using TestClass;

static void UpdateL1TableWorker()
{
     strTest tS = new strTest();
     testClass tC = new testClass();

     int i = 1;
     int j = 2;
     tS.iA = 100;
     tS.iB = 200;
     tS.iC = 300;
     tS.iD = 400;
     tS.boA = (i == 1 ? true : false);
     tS.boB = (j > 3 ? true : false);
     tC.useStruct(ts);
}

This class uses the structure’s values:

using System;
using TestStruct;

public void useStruct(strTest tS)
{
     Console.WriteLine("iA: {0}  iB: {1}  iC: {2}  iD: {3}", tS.iA, tS.iB, tS.iC, tS.iD)
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: