user2395615
user2395615

Reputation: 35

Is there a working alternative to if(struct == null)?

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;
    }

Upvotes: 3

Views: 9678

Answers (3)

Andy
Andy

Reputation: 33

In the following code, we create and implement an implicit boolean operator that handles one approach to determining if a struct has been initialized (a struct is never null, as they are value types. However their members can be null).

struct Foo
{
    float x;
    public static implicit operator bool(Foo x)
    {
        return !x.Equals(default(Foo));
    }
}

Note: this will return a false negative when x == 0. Keeping this in mind, you can creatively code a workaround depending on your specific needs.

The simplest work around would be to create a dummy class (eg nullable) which you initialize in the constructor of the struct, and ensure to always initialize said struct through the use of a constructor:

public class nullable{}
struct Foo
{
    nullable n;
    float x;
    public Foo(float x)
    {
        this.x = x;
        this.n = new nullable();
    }
    public static implicit operator bool(Foo x)
    {
        return !x.Equals(default(Foo));
    }
}

Usage:

if(mFoo)
{
    //Do something
}

Upvotes: 0

HugoRune
HugoRune

Reputation: 13809

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];

Upvotes: 6

Marcelo de Aguiar
Marcelo de Aguiar

Reputation: 1442

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.

Upvotes: 1

Related Questions