Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 528
fdgfdgs dfg Avatar asked Jul 31 '12 10:07

fdgfdgs dfg


1 Answers

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.

like image 88
Habib Avatar answered Oct 11 '22 23:10

Habib