title: Initializing stored procedure output parameter
body: <p>I have a simple SQL Server stored procedure:</p>
  
  <pre><code>ALTER PROCEDURE GetRowCount
  
  (
  @count int=0 OUTPUT
  )
  
  AS
  Select * from Emp where age&gt;30;
  SET @count=@count+@@ROWCOUNT;
  
  RETURN
  </code></pre>
  
  <p>I am trying to initialize and access the output parameter in the following C# code:</p>
  
  <pre><code>SqlConnection con = new SqlConnection();
  con.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True";
  
  SqlCommand cmd = new SqlCommand();
  cmd.Connection = con;
  
  cmd.CommandText = "GetRowCount";
  cmd.Parameters.Add(new SqlParameter("@count", SqlDbType.Int));
  cmd.Parameters["@count"].Direction = ParameterDirection.Output;
  con.Open();
  cmd.Parameters["@count"].Value=5;
  cmd.ExecuteNonQuery();
  
  int ans = (int)(cmd.Parameters["@count"].Value);
  Console.WriteLine(ans);
  </code></pre>
  
  <p>But on running the code, an <code>InvalidCastException</code> is being thrown at the second last line of the code (I debugged and checked that nothing is being returned in the Value attribute). </p>
  
  <p>How can I properly initialize the output parameter in code? Thanks in advance!</p>