tags:

views:

3104

answers:

4

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?

+3  A: 
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?

Nicholas Mancuso
array.Count > 0This was precisly what I was looking for :)Thanks for the very quick answer.
Patrik Björklund
+2  A: 

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.

mquander
should probably make sure that rummen isn't null before checking upperbound.
Jeff Martin
A: 

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)

ShuggyCoUk
+1  A: 

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

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