System.NullReferenceException

capri

Active member
Joined
Jun 16, 2015
Messages
42
Programming Experience
5-10
Hi,


I have an Interface. I call the interface from my form as this.


C#:
IExample myExample = null;


myExample.Height = 12;


But I get error that myExample is null.


Could I know what is the solution please?


Thanks
 
It's a concern that you're at the point of trying to use an interface and can't see the glaring problem with that code. Why would you be surprised that your variable is null when your code explicitly assigns null to the variable? If you want to be able to set the Height of an object then you have to actually assign an object to that variable. Given that the variable is type IExample, the object you assign must be a type that implements that interface.
 
I think maybe you don't understand how interfaces work. An interface basically tells you that a type implementing it is guaranteed to have a specific set of members. The interface guarantees that those members will exist but it doesn't provide any implementation or place any restrictions on what implementations can be used. In order for your code to work, you must first define a class that implements the IExample interface and then you must create an instance of that class and assign it to your variable.

With just that information, many wonder what use interfaces are when they start out. One of the most obvious examples that I can think of is when using data-binding in Windows Forms. The DataSource property of controls like ComboBox, ListBox and DataGridView is type Object. That means that you can theoretically assign any object to that property. If the object you assign does not implement either the IList or IListSource interface though, an exception will be thrown. That's because, internally, those controls assume that the set of members defined by the IList interface will be accessible. It doesn't care how they're implemented; only that they're there.
 
Back
Top Bottom