Local variable Question
This is just a logical problem check. I have the following block of code:
The attempt to call the member function is generating the the following Error: Use of unassigned local variable, does this mean the assignment is only valid within the logical parentheses block? I know if the if statement within which assignement takes places evaluates to false the variable will never be assigned.
for (int i = 0; i < deviceCount; i++)
uint pcbSize = 0;
DeviceInfo dInfo; <==== Declared here within the for loop
deviceName = string.Empty;
RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(new IntPtr((devList.ToInt32() +
(dwSize * i))), typeof(RAWINPUTDEVICELIST));
GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);
if (pcbSize > 0)
IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
deviceName = (string)Marshal.PtrToStringAnsi(pData);
if (rid.dwType == RIM_TYPEKEYBOARD || rid.dwType == RIM_TYPEHID || rid.dwType == RIM_TYPEMOUSE)
dInfo = new DeviceInfo(); <== assignment starts here
dInfo.deviceName = (string)Marshal.PtrToStringAnsi(pData);
dInfo.deviceHandle = rid.hDevice;
dInfo.deviceType = GetDeviceType(rid.dwType);
string DeviceDesc = ReadReg(deviceName);
dInfo.deviceName = DeviceDesc;
dInfo.outputDeviceInfo(); <== An attempt to call member function here. (Still within for loop block code)
}//end for loop
And that's why it generates a compile-time error -- not all code paths have an assignment. The assignment itself is valid both inside and outside the block of code, that's not an issue. The issue is that if the condition is false, the variable never gets assigned at all.
Originally Posted by WDT
The simple way to fix this (assuming you're really sure you want to potentially access an uninitialized variable) would be to change the variable declaration to "DeviceInfo dInfo = null;"
Of course, the *better* fix is to move the use of the variable into the if statement, as there's frankly no reason not to; you don't want that line called unless the condition was true.
I moved it back into the If Statement. I just wanted it separately for formatting reasons.