Fixing the 'Use of unassigned local variable' with a null assignment. Why?

后端 未结 4 1950
滥情空心
滥情空心 2020-12-18 17:24

With a piece of code like this, the compiler complains on c.MyProperty:

MyClass c;

try { throw new Exception(); }
catch (Exception) { }

c.MyPr         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-18 18:21

    The reason for this exception is that you've not assigned a default value for the variable e.g

    if (Request.Files != null  && Request.Files.Count > 0)
                {
                     Image = Request.Files.AllKeys[0];
                }
    var stream  = new FileStream(Image,FileMode.Open);
    

    now the Image variable will give compiler error

    Use of unassigned local variable 'Image'

    That is due to the reason that there is possibility that condition becomes true and control will never get to know what the Image variable is . so either place an else block or assign a default value as below.

    string Image = "";
    if (Request.Files != null  && Request.Files.Count > 0)
                {
                     Image = Request.Files.AllKeys[0];
                }
    var stream  = new FileStream(Image,FileMode.Open);
    

提交回复
热议问题