-1

This code:

int a;
if(a==1){ do something}

or

Image img;
   if(img!=null){do something}

These codes generates the error:

Use of unassigned local variable 'variable-name'

I know what exactly this error says and how to resolve it. but what I wonder is that

  1. Shouldn't a variable that is declared and not assigned a value, have a value? like null for the Image

2.Why wouldn't it allow to even compare the variable? it can simply say that it doesn't match.

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • The use of an uninitialized variable is usually a bug. It probably stems from C/C++ when an uninitiazlized variable could have random data in it. – D Stanley Oct 08 '16 at 23:11

1 Answers1

2
  1. Shouldn't a variable that is declared and not assigned a value, have a value? like null for the `Image'

No. That's just not the way the language is defined. Local variables do not have default values in C# (or most other languages, but by no means all).

2.Why wouldn't it allow to even compare the variable? it can simply say that it doesn't match.

Because you're trying to read the value of a variable that you've never assigned a value to, which is a bug (in C#) by definition. Thus, it's calling your attention to that bug.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875