0

why the following code doesn't work?

internal static string[] GetToolsForRole(string selectedRole) {
  string[] tempStr;
  ArrayList myAL = new ArrayList();
  SqlCommand cmd = new SqlCommand("usp_TD_SelectByRoleName");
  cmd.CommandType = CommandType.StoredProcedure;

  cmd.Parameters.Add("@role", SqlDbType.NVarChar, 50).Value = selectedRole;

  SqlConnection myConnection = Util.GetConnection();
  cmd.Connection = myConnection;
  SqlDataReader reader = cmd.ExecuteReader();

  int i = 0;
  while (reader.Read()) {
    tempStr[i] = reader["TD_Name"].ToString();
    i++;
  }

  return tempStr;
}
6
  • Just wondering, why not ArrayList? Sure List<T> is strongly typed, but with just strings isn't ArrayList just fine? Commented Mar 20, 2011 at 16:33
  • @Hogan: Huh? How is ArrayList any better with strings? You should always use List<T>. Commented Mar 20, 2011 at 17:25
  • @SLaks : I would guess it was marginally faster unless it is implemented strangely. Commented Mar 20, 2011 at 17:31
  • @Hogan: An ArrayList will never be faster than a List<T>. (I have no sources for that statement) Commented Mar 20, 2011 at 17:33
  • @Slaks : My understanding is parameterized types are instantiated at runtime -- this would have to require more overhead in time and memory than pre-compiled code which just manages pointers. Am I missing something? (I will admit we are talking about relatively small differences). Commented Mar 20, 2011 at 17:57

2 Answers 2

2

Arrays don't work like that.

You should use a List<string>, and call the Add method.

To use an array,you need to create a new array by writing tempStr = new string[size]. Arrays cannot be resized in-place.

Sign up to request clarification or add additional context in comments.

2 Comments

i changed to List<string>, but still get "Use of unassigned local variable 'tempStr'"
@eyalb: You need to put a new List<string> into your variable.
0

You never allocate tempStr.

Try this in loop:

myAL.Add(reader["TD_Name"].ToString());

Then this at return

return (String[]) myAL.ToArray( typeof( string ) );

You won't need (remove) the i and tempStr variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.