3

I'm trying to check if a struct from an array has been assigned, I can't check it or it's data for null. Is there a way I can check if it has been assigned yet?

Struct:

    [StructLayout(LayoutKind.Explicit)]
    public struct CharInfo
    {
        [FieldOffset(0)]
        public CharUnion Char;
        [FieldOffset(2)]
        public short Attributes;
    }

Method

    public void render(){
        for (int i = 0; i < (width * height - 1); i++) {
            if (screenBuffer[i].Char.UnicodeChar != Convert.ToChar(" ")) {
                ScreenDriver.screenBuffer[i] = screenBuffer[i];
            }
        }
       // ScreenDriver.screenBuffer = screenBuffer;
    }
Murilo
  • 1,054
  • 1
  • 14
  • 31
user2395615
  • 35
  • 1
  • 5

2 Answers2

3

You can compare the struct to its default value: if (struct==default(CharInfo). However this cannot differentiate between an uninitialized struct and a struct initialized with zeroes. This is because there are no such things as uninitialized structs, a struct is always automatically initialized.

If you can extend the struct, you can give it a bool IsAssigned. Default initialization will set this to false. Another option is to wrap it in a nullable:
CharInfo?[] screenBufferWithNull = new CharInfo?[123];

If extending the struct, or replacing it with a nullable<struct> is not desired, and you want to keep an aray of structs as in your example, the easiest workaround is to keep this information in a separate array of bools:
bool[] screenbufferIsAssigned = new bool[screenbuffer.Length];

HugoRune
  • 12,320
  • 6
  • 61
  • 137
  • Another option is to have an item in the enumeration be very specifically not initialized. For example enum Test { NotIntialized = 0, Red, Green, Blue }. the value 0 is the default. – btlog Sep 13 '15 at 01:05
1

Structs cannot be null as they are value types. Instead you can compare the to its default value using default(CharInfo) or create a Nullable.

Marcelo de Aguiar
  • 1,412
  • 12
  • 30
  • Thanks, but now I'm getting a new error. "Error 2 Operator '!=' cannot be applied to operands of type 'SharpTUI.Krn32.Kernal32.CharInfo' and 'SharpTUI.Krn32.Kernal32.CharInfo' " – user2395615 Sep 13 '15 at 00:41
  • Thats because you need to overload the operators for your struct as seen in this question http://stackoverflow.com/questions/15199026/comparing-two-structs-using – Marcelo de Aguiar Sep 13 '15 at 00:44