Get Off My Lawn
Get Off My Lawn

Reputation: 36311

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?

Upvotes: 3

Views: 6137

Answers (1)

Eugene
Eugene

Reputation: 1533

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>>();

Upvotes: 7

Related Questions