Sam Oyl
Sam Oyl

Reputation: 381

Function stops when (If Statement) ends

I have this function written in a project to locally save some details about the users` accounts

public void Forward(string Path,string Name,List<string> AttributeName = null,List<string> AttributeValue = null,string Value = null, int NumberOfNames = 1,bool EndA = true,bool EndB = true)
{
        <codes>
        */if (!AttributeName .Contains(null) || AttributeName .Contains(""))
        {
            var Text1 = AttributeName;
            var Text2 = AttributeValue;
            var BothText = Text1.Zip(Text2, (t1, t2) => new { Word1 = t1, Word2 = t2 });
            foreach (var tt in BothText)
            {
                Lab.SaveAttribute(tt.Word1, tt.Word2);
            }
        }
     **/if (!Value.Contains(null) || Value.Contains(""))
        {
            <codes>
        }
        if (EndA)
        {
            <codes>
        }
        if (EndB)
        {
            <codes>
        }
}

The problem is that when the first If Statement which marked with */ ends, the whole Function ends without reaching the second if Statement which marked with **/.

Note that this only happens when the AttributeName is null or ""

why is this happening or what am i doing wrong?

Upvotes: 0

Views: 69

Answers (3)

Damith
Damith

Reputation: 2082

public void Forward(string Path,string Name,List<string> AttributeName = null,List<string> AttributeValue = null,string Value = null, int NumberOfNames = 1,bool EndA = true,bool EndB = true)
{
        <codes>
        */if (!AttributeName.Equals(null) || AttributeName.Equals(""))
        {
            var Text1 = AttributeName;
            var Text2 = AttributeValue;
            var BothText = Text1.Zip(Text2, (t1, t2) => new { Word1 = t1, Word2 = t2 });
            foreach (var tt in BothText)
            {
                Lab.SaveAttribute(tt.Word1, tt.Word2);
            }
        }
     **/if (!Value.Equals(null) || Value.Equals(""))
        {
            <codes>
        }
        if (EndA)
        {
            <codes>
        }
        if (EndB)
        {
            <codes>
        }
}

Upvotes: 1

Sean
Sean

Reputation: 62472

If AttributeName is null then your call to AttributeName.Contains will throw a NullReferenceException. That's why your method is exitting.

You're also passing null into Contains. If you look at the documentation for Contains you'll see that it throws an ArgumentNullException if you pass in null. What are you expectingContainsto do when you pass innull`..?

I'm guessing that somewhere up the call stack you're catching this exception and silently ignoring it! Step through the code with your debugger and you'll see the problem immediately.

Upvotes: 2

Roland B&#228;r
Roland B&#228;r

Reputation: 1730

If AttributeName is null AttributeName.Contains(null) will throw a NullReferenceException.

Check first if AttributeName != null before you access any member functions.

Upvotes: 2

Related Questions