You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all. t
- Object variables that are uninitialized and hence point to nothing. In this case, if you access members of such objects, it causes a
NullReferenceException. - The developer is using
nullintentionally to indicate there is no meaningful value available. Note that C# has the concept of nullable datatypes for variables (like database tables can have nullable fields) - you can assignnullto them to indicate there is no value stored in it, for exampleint? a = null;(which is a shortcut forNullable<int> a = null;) where the question mark indicates it is allowed to storenullin variablea. You can check that either withif (a.HasValue) {...}or withif (a==null) {...}. Nullable variables, likeain this example, allow to access the value viaa.Valueexplicitly, or just as normal viaa.
Note that accessing it viaa.Valuethrows anInvalidOperationExceptioninstead of aNullReferenceExceptionifaisnull- you should do the check beforehand, i.e. if you have another non-nullable variableint b;then you should do assignments likeif (a.HasValue) { b = a.Value; }or shorterif (a != null) { b = a; }.
public class Person
{
public int Age { get; set; }
}
public class Book
{
public Person Author { get; set; }
}
public class Example
{
public void Foo()
{
Book b1 = new Book();
int authorAge = b1.Author.Age; // You never initialized the Author property.
// thereThere is no Person to get an Age from.
}
}
Here comboBox1 is created before label1. If comboBox1_SelectionChanged attempts to reference `label1label1, it will not yet have been created.