Use of unassigned local variable - if statements

萝らか妹 提交于 2019-12-06 03:59:23

when declaring string strType you must assign a value, something like

string strType = null;

More details: Compiler Error CS0165

The reason for this is that you are not assign strType variable to any value before you use it. According to C# compiler rules you must assign variable to any value before you begin to use it in any way.

In other words, what should be enough is assign an empty string before consditions, like shit for example:

strType = srting.Empty; //at least one value is already assigned!

while (rsData.Read())
{
    .... //your code here
}

Why this? To avoid ambiguity and not clear code presentation.

More on this, dierctly read a small article from Eric Lippert: Why are local variables definitely assigned in unreachable statements?

It complains because at the time of If statment the variable has not got any value.

just do string strType = "";

You should assign some value to local variable before you use it. You can initialize it in place where you declare it (before while block):

var strType = ""; // or null

Or (if you don't want strType to remember its value from previous iteration), make sure it gets initial value both when reader contains data, or when there is DbNull

strType = rsData["TYPE"] == DBNull.Value ? "" : rsData["TYPE"].ToString().Trim();

be nice, use String.Empty;

string strType=String.Empty;

This error means you didn't previously declare that variable. Just initialise those variables in the beginning of your while loop.

Example:

while (rsData.Read())
{
    string strType = string.Empty;
    string strwho = string.Empty; // Do this if you have the same error for strwho
    string strmetades = string.Empty; // Do this if you have the same error for strmetades

    // Your other code comes here
}

If you order your IF statements a little different, you can even avoid the reassigning of an empty value to the variable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!