Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a nullable struct?

I have a method that I would like to return either PrefabItem or null. However, when I do the below, I get an error:

Cannot convert null to 'PrefabItem' because it is a non-nullable value type

struct PrefabItem { }

public class A {
  int prefabSelected = -1;
  private static List<PrefabItem> prefabs = new List<PrefabItem>();

  private PrefabItem GetPrefabItem() {
    if (prefabSelected > -1) {
      return prefabs[prefabSelected];
    }
    return null;
  }
}

I saw that I could use Nulllable<T>, but when I do so I get the same message.

struct PrefabItem { }

struct Nullable<T> {
  public bool HasValue;
  public T Value;
}

public class A {
  int prefabSelected = -1;
  private static Nullable<List<PrefabItem>> prefabs = new Nullable<List<PrefabItem>>();

  private PrefabItem GetPrefabItem() {
    if (prefabSelected > -1) {
      return prefabs.Value[prefabSelected];
    }
    return null;
  }
}

What do I need to do to get my method to return PrefabItem or null?

like image 916
Get Off My Lawn Avatar asked Oct 29 '25 19:10

Get Off My Lawn


1 Answers

You should return either Nullable< PrefabItem > or PrefabItem?

Example of null-able syntax:

  private PrefabItem? GetPrefabItem() {
    if (prefabSelected > -1) {
      return prefabs[prefabSelected];
    }
    return null;
  }

One more comment. If you need List of null-able elements, declaration of the list should be either:

private static List<PrefabItem?> prefabs = new List<PrefabItem?>();

or

private static List<Nullable<PrefabItem>> prefabs = new List<Nullable<PrefabItem>>();
like image 78
Eugene Avatar answered Nov 01 '25 10:11

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!