-2

I made a code with php and now I'm trying to convert this in C#, but it isn't working

This is the php code:

ERROR:

An unhandled exception of type 'System.NullReferenceException' occurred in connectiondb.exe

Additional information: De objectverwijzing is niet op een exemplaar van een object ingesteld.

In C# there's something wrong with the: if statement, but I can't find the problem. Can someone help me?

Community
  • 1
  • 1
Test
  • 45
  • 1
  • 7

1 Answers1

1

As he mentioned in the comment, this will explain that very clearly, Letme add few more words. In C# you will get NullReference Exception only when you are accessing value from null(Which means not existing).

Consider the following scenario:

You are assigning a work to the compiler to take check/iterate a collection. When compiler is going to do that process he is not able to find the location that you specified. Then it returns to you with the message that the specified thing is not found, i cannot proceed the action. You are getting this response message from the compiler as exception.

In the example that you have given, You are assigning the task "Iterate the Something that is null/ search something inside a memory location that is null. both are not possible since they are not existing in the memory.

What you can do to avoid this is, check for null before accessing the the value: consider the following changes in the signature:

public bool isDeelverzamelingVan(List<int> eersteVerzameling, List<int> tweedeVerzameling)
{
    if(eersteVerzameling==null || tweedeVerzameling==null)
    {
        return false;
    }
    foreach (int element in eersteVerzameling)
    {
        if (!tweedeVerzameling.Contains(element))
        {
           return false;
        }         
    }
    return true;
}

So the output will be false if anyone of the collection is null; and hence you can avoid throwing exception

Community
  • 1
  • 1
sujith karivelil
  • 27,818
  • 6
  • 51
  • 82