lundi 26 avril 2021

Assign variable and check it within an IF evaluation

I doubt this can be done but I'll ask anyway since it would make my code much more readable.

I have to control a large string for various substrings and elaborate it in different ways depending on the substring found.

At the moment I have a nested if like

position = mystring.IndexOf("my substring")
if (position>0)
{
    position = mystring.IndexOf("somestring", position);
    [...]
}
else
{
    position = mystring.IndexOf("my substring2")
    if (position>0)
    {
        position = mystring.IndexOf("somestring2", position);
        [...]
    }
    else {...}
}

The only other way I can think of doing this is double casting the IndexOf function:

if (mystring.IndexOf("my substring")>0)
{

    position = mystring.IndexOf("somestring", mystring.IndexOf("my substring"));
    [...]
}
else if (mystring.IndexOf(mysubstring2)>0)
{
    position = mystring.IndexOf("somestring2", mystring.IndexOf("my substring2"));
    [...]
}
else {...}

Is there a way to check the IndexOf() result and assign it to a variable all within the if() statement?

Something on the line of

if ((position = mystring.IndexOf("my substring")) AndAlso position > 0) { ... }

or any tip on having such a piece of code handled better?

Aucun commentaire:

Enregistrer un commentaire