Home > front end >  Checking for null/empty arrays in a Unity c# script
Checking for null/empty arrays in a Unity c# script

Time:04-22

I have a Unity game using WebGL and c#.

I am running Unity 2020.2.6f1, from what I understand is using c# 7.3

I currently check for null or empty arrays like this:

ObjectType[] myObjectTypeList = FindObjectsOfType<ObjectType>();

if(myObjectTypeList != null && myObjectTypeList.Length > 0)
{
    ...
}

But I read that in c# 7 you can shorten to this:

if(!(myObjectTypeList?.Length != 0))
{
    ...
}

Is this something I can do in a Unity c# script when I am using FindObjectsOfType?

Thanks!

CodePudding user response:

In C#7 C# 8.0 you can use the is operator and, your if statement could be

if (myObjectTypeList is {Length: > 0}){
    // [...]
}

which is equal to

if (myObjectTypeList != null && myObjectTypeList.Length > 0){
    // [...]
}

Edit

This answer is wrong.

According to Microsoft's Documentation:

Beginning with C# 8.0, you use a property pattern to match an expression's properties or fields against nested patterns [...]

This feature works only from c#8.0 and later. That said, this answer will still work, since Unity Version 2020.2 uses Roslyn Compiler with C# 8.0 Language Support.

CodePudding user response:

The ?. is called the Null Conditional Operator. a?.b will resolve to b, unless a is null, in which case it resolves to null. This operator was actually new since C# 6.0.

CodePudding user response:

If you can live with the warnings you will get about calling an extension method on a null, this should work:

public static class Extensions
{
    public static bool NotNullHasItems<T> (this IEnumerable<T> collection)
    {
        if (collection == null)
        {
            return false;
        }
        return collection.Any();
    }
}

To test this, I used:

List<string> stuff = null;
var shouldBeFalse = stuff.NotNullHasItems();
stuff = new List<string>();
var shouldAlsoBeFalse = stuff.NotNullHasItems();
stuff.Add("test");
var shouldBeTrue = stuff.NotNullHasItems(); 

and both shouldBeFalse and shouldAlsoBeFalse ended up false while shouldBeTrue was true.

You may want a better name (perhaps reverse the logic and name it IsNullOrEmpty to match string.IsNullOrEmpty)

  • Related