Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c# - Error : The Out Parameter must be assigned before control leaves the current method

While sending back parameters getting this error

Error : The Out Parameter must be assigned before control leaves the current method

Code is

 public void GetPapers(string web, out int Id1, out int Id2)
    {
        SqlConnection conn = new SqlConnection(ConnectionString());
        conn.Open();
        SqlCommand cmd = new SqlCommand("GetPapers", conn);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add(new SqlParameter("@URL", String(web)));

        SqlDataReader rdr = cmd.ExecuteReader();

        if (rdr.Read())
        {
            Id1 = (int)rdr["ID1"];
            Id2 = (int)rdr["ID2"];
        }

        rdr.Close();
    }

calling it as

GetPapers(web, out Id1, out Id2);

Related to this question

Related question

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are assigning Id1 and Id2 inside an if statement and compiler can't determine if it will be assigned a value at run time, thus the error.

You could assign them some default value before the if statement. Something like.

Id1 = 0;
Id2 = 0;

if (rdr.Read())
{
    Id1 = (int)rdr["ID1"];
    Id2 = (int)rdr["ID2"];
}

or specify some default values in else part of your condition.

An out type parameter must be assigned some value, before the control leaves the functions. In your case, compiler can't determine whether your variables will be assigned or not, because it is being assigned inside an if statement.

See: 5.3 Definite assignment

At a given location in the executable code of a function member, a variable is said to be definitely assigned if the compiler can prove, by static flow analysis, that the variable has been automatically initialized or has been the target of at least one assignment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...