Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Problem
Error out parameter must be assigned before control leave current method .
function GetInsertStatmentText below return full insert statement as below
INSERT INTO master_table(id, branch_id, name, address, phone) VALUES(@id, @branch_id, @name, @address, @phone);

in out paramter i need to return
@id, @branch_id, @name, @address, @phone

when i add out parameter to function i get error

Error  out parameter must be assigned before control leave current method

How to solve this error please ?

What I have tried:

public static string GetInsertStatmentText(string JsonData,out  sqp)
        {
            string Insert = "";
            JObject jo = JObject.Parse(JsonData);
            JToken m = jo["master"];
            string connectionstring = "Server=AHMEDSALAH-PC\\SQL2014;Database=Atum;User Id=sa;Password=abc123;"; //change connection string
            using (SqlConnection connection = new SqlConnection(connectionstring))
            {
                using (SqlCommand command = new SqlCommand(JsonHelper.GetInsertStatement(m), connection))
                {
                    connection.Open();
                    List<SqlParameter> lsp = JsonHelper.GetSqlParams(jo["master"]);
                    foreach (SqlParameter sqp in lsp)
                        command.Parameters.Add(sqp);
                    Insert = command.CommandText;
                }
            }
            return Insert;

        }
Posted
Updated 14-Aug-19 9:11am
v2

1 solution

There is a difference between parameters and local variables.
When you do this:
foreach (SqlParameter sqp in lsp)
You create a new local variable of the same name as the parameter, and scope it to the foreach block.
As a result, your function never assigns a value to the parameter sqp - and since it is declared as an out parameter the system requires a value be assigned to it before the method exits, regardless of which path it takes through the method. If any path does not assign a value, you will get an error, and your code will not compile.
 
Share this answer
 
Comments
ahmed_sa 14-Aug-19 15:18pm    
thank you for reply what i need is to get parameters as return of function
can you help me on any way i will accept
ahmed_sa 14-Aug-19 15:20pm    
meaning how to solve this error or how to modify function to remove this error
OriginalGriff 14-Aug-19 15:37pm    
Assign a value to sqp before it hits the return statement?
ahmed_sa 14-Aug-19 15:42pm    
how i do that
OriginalGriff 14-Aug-19 16:03pm    
You are kidding, right?

sqp = "...";
return Insert;

What you want to return, I have no idea - it's your app, not mine, and I don't have a clue what you are trying to do ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900