Cannot implicitly convert type Windows.Devices.Enumeration.DeviceWatcher to DeviceWatcher

357 views Asked by At

I'm building an IoT app that needs to detect when a removable device was inserted and removed. I'm getting the following error when trying to create a DeviceWatcher object.

The DeviceWatcher.CreateWatcher() method is of type DeviceWatcher. Why would I be getting this error?

I'm not sure what the problem is and I don't know how to solve this. Can anyone give insight here?

DeviceWatcher watcher = DeviceInformation.CreateWatcher(DeviceClass.PortableStorageDevice);

Error:

Cannot implicitly convert type 'Windows.Devices.Enumeration.DeviceWatcher' to 'NamespaceName.DeviceWatcher'

Application Type:

Windows 10 Background Application. Anniversary Edition.

Manifest Capability:

Removable Storage

2

There are 2 answers

2
Bozhidar Stoyneff On BEST ANSWER

Try implicit variable declaration:

var watcher = DeviceInformation.CreateWatcher(DeviceClass.PortableStorageDevice);

FURTHER EXPLANATION

By implicit declaration you are actually letting the compiler to do its magic (an intelligent guess) and derive the type of the variable, being declared based on the data type returned on the right. Basically your mistake is the assumption that the watcher variable should be of type DeviceWatcher but it isn't. At least not the one you've typed. Ther is a probably a conflict within your using statements, and the DeviceWatcher defaults to something different than Windows.Devices.Enumeration.DeviceWatcher which is the correct type returned by the DeviceInformation.CreateWatcher()

0
Brian On

Using var is one option. You could also specify the namespace explicitly:

Windows.Devices.Enumeration.DeviceWatcher watcher = DeviceInformation.CreateWatcher(DeviceClass.PortableStorageDevice);