Home > front end >  How are arrays of structures allocated in C#
How are arrays of structures allocated in C#

Time:10-19

I am trying to allocate an array of structures in C#. For example,

public struct Channel {
    int ChannelId;
    // other stuff goes here... 
}

public  struct FrameTraffic {
    public int FrameId;
    public int MaxChannels;
    public Channel[] Channels;

    public FrameTraffic(int dummyCS0568 = 0)
    {
        this.FrameId = 0;
        MaxChannels = TableMgr.MaxChannels;
        Channels = new Channel[TableMgr.MaxChannels];
    }
}

But when I go to allocate an array of FrameTraffic structures, I see that Channels is null. This tells me that Channels is a reference rather than an array of structures. Am I correct? If so, then allocating the Channels array shouldn't embed the array into the structure, but simply satisfy the reference in the structure. I want the structures embedded. Is there a way to do this? Or am I incorrect in my assumptions?

CodePudding user response:

Answering the later part of your question and disregarding any other problem. Yes you are correct, this will be a reference to an array. However, if you wanted to embed the array in the struct you can use a enter image description here

There are two things that i think is possibly causing this :

  • You are just initializing the array with size but not assigning any values
  • You might be initializing FrameTraffic with default construct instead of what you have defined (this caused the actual NPE for me)

Below is how you can adjust your code: (I have hardcoded values which is brought by TableMgr.MaxChannels since i dont have that)

class Program
{
    static void Main() 
    {
        FrameTraffic fT = new FrameTraffic(0);
        foreach (var item in fT.Channels)
        {
            Console.WriteLine(item.ChannelId);
        }
        Console.Read();
    }
}

public struct Channel
{
    public int ChannelId; //missing public exposer if you really want to reassign
    // other stuff goes here... 
}

public struct FrameTraffic
{
    public int FrameId;
    
    public Channel[] Channels;

    public FrameTraffic(int dummyCS0568 = 0)
    {
        this.FrameId = 0;
        const int MaxChannels = 1;
        //array requires size and its values assigned here 
        Channels = new Channel[MaxChannels]{ new Channel { ChannelId = 1 } };
    }
}
  • Related