开发者

strange exception in .aspx page

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: 开发者_如何学JAVAUse 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?


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.


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜