Patrik Björklund
Patrik Björklund

Reputation: 1237

How to check if an array exists in C#?

Is there any way to check if a array exists or has a value in a specific element?

I have this line of code

if (rummen[positionX, positionY].Levandesaker[0].alive == true)

And it works fine as long as it exists. But what I want to do is

if (rummen[positionX, positionY].Levandesaker != null)
{
    if (rummen[positionX, positionY].Levandesaker[0].alive == true)
    {
    }
}

Does anyone know what Im after or can help me out with what im looking for?

Upvotes: 1

Views: 8683

Answers (4)

Dercsár
Dercsár

Reputation:

If you want to check if something is an array or not, check for the Array type:

if (rummen[positionX, positionY].Levandesaker is Array) { ... }

Upvotes: 1

mqp
mqp

Reputation: 71937

I hope I interpreted this question right!

An array is of constant size, and contains a value for every index from 0 to the upper bound of the array.

So to check whether a position in the array exists, you can just make sure it's less than the upper bound. Something like this should cover absolutely every condition (assuming rummen itself is not null!):

// make sure rummen contains the [positionX, positionY] element
if(rummen.GetUpperBound(0) > positionX && rummen.GetUpperBound(1) > positionY)
{
    if(rummen[positionX, positionY].Levandesaker != null)
    {
        // make sure Levandsaker contains at least one element
        if(rummen[positionX, positionY].Levandsaker.Length > 0)
        {
            if(rummen[positionX, positionY].Levandesaker[0].alive == true)
            {
            }
        }
    }
}

EDIT: Sorry, fixed C#-specific syntax. Also added a check on Levandsaker for demonstration purposes.

Upvotes: 3

ShuggyCoUk
ShuggyCoUk

Reputation: 36438

the array aspect is immaterial (your code already assumes the entry is non null)

I assume the following:

public class Rummen
{
    public property Levandesaker { get; }
}

public class Levandesaker
{
    public bool alive
}

which lets you do:

public static bool LevandesakerExistsAndAlive(this Rummen r)
{
    return (r.Levandesaker != null && r.Levandesaker.alive);     
}

if (rummen[positionX, positionY].LevandesakerExistsAndAlive())
{
}

note that this assumes you do not control the Rummen class (otherwise you could simply make this an instance method or property and be done with it)

Upvotes: 0

Nicholas Mancuso
Nicholas Mancuso

Reputation: 11877

if (rummen[positionX, positionY].Levandesaker != null &&
    rummen[positionX, positionY].Levandesaker.Count > 0)
{
    if (rummen[positionX, positionY].Levandesaker[0].alive == true)
    {
    }
}

I'm not entirely sure which array you're talking about now that I think about it. Are you referring to Levandesaker or rummen?

Upvotes: 3

Related Questions