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