0

I have aspx page on which i have something like that:

<%
    string image;
    if(cond)
       image = "somestring";
%>

...

<% if (cond) { %>
    <img src="<%= image %>" /> <!-- HereI get CS0165 exception: Use of unassigned local variable 'image' -->
<% } else { %>
    <div> ... </div>
<% } %>

So my question is why I get the exception? If I write string image = ""; this exception goes away. That's very strange. I guess that the exception has something to do with presentation of aspx page. Can someone explain why this happens?

devfreak
  • 1,201
  • 2
  • 17
  • 27
  • If you really want to know how your page gets compiled, you can configure MVC to compile the view when you build. It can be very enlightening to see the errors in a more familiar context: http://stackoverflow.com/questions/383192/compile-views-in-asp-net-mvc – spender Nov 18 '10 at 21:04

3 Answers3

8

When you declare your variable image, give it an initial value.

string image = "";

The error you are getting indicates that the variable has not been initialized in all cases (it only gets initialized if cond is true).

This has nothing to do with being contained in a .aspx page. You will get the same error in a code behind.

Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
  • Thanks. I'm coming from the C++ land, there you have full control over this staff, I guess I have to get used to all limitations in c#. – devfreak Nov 18 '10 at 21:05
  • 3
    Many of the benefits of "full control" simply mean allowing you to shoot yourself in the foot with a telescopic sight. It's not a limitation... the compiler's doing you a big favour here. – spender Nov 18 '10 at 21:09
  • 1
    +1 to spender. The compiler is helping you not make silly mistakes. What you call limitation, I call automation of mundane tasks. – CatDadCode Nov 18 '10 at 21:11
1

Or even better would be to add an else to your if to set to the default value:

string image;
if(cond)
  image = "somestring";
else
  image = String.Empty;
Bryan
  • 2,775
  • 3
  • 28
  • 40
  • Yes that is slightly better, because this way we have one less assignment. Thanks – devfreak Nov 19 '10 at 09:16
  • @devfreak You can have 0 assignments by making the image server side then set its source directly: if (cond) Image1.Src = "somestring"; else Image1.Src = "somethingelse"; – Shadow The GPT Wizard Nov 19 '10 at 21:08
1

If you're after the reason rather than the solution (that you already know) - when you declare a variable nothing happens. Only when you assign something the compiler will reserve memory space and everything.

So trying to access variable that is not yet initialized is not valid because there's nowhere in the memory of the machine to go to... there's nothing yet.

It's like trying to lift a bucket that is not there: it's not empty bucket.. it's not a full bucket.. there's no bucket to lift.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208