Can't assign variable, and access it

I'm feel like I'm missing a detail

Page 1 of 1

11 Replies - 3011 Views - Last Post: 28 February 2008 - 11:42 PM Rate Topic: -----

#1 Footsie  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 370
  • Joined: 20-September 07

Can't assign variable, and access it

Posted 28 February 2008 - 07:36 AM

I'm having trouble accessing a variable within a while loop which is inside a try{} block.

The error is: Use of unassigned local variable 'vehicleID'.

   
     string vehicleID;
        try
        {
            conn.Open();
            reader = com.ExecuteReader(Commandbehavior.CloseConnection);
            while (reader.Read())
            {

//this is where I am attempting to assign the vehicleID variable to the 
//result of the getstring method
               vehicleID = reader.GetString(0);
            }
        }

        catch (Exception exc)
        {
            lblException.Visible = true;
            lblException.Text = "There is a problem with your connection:  " + exc.ToString();
        }
        finally
        {
            conn.Close();
        }

       // get result from SELECT above and convert to int
        int vehicle = Convert.ToInt16(vehicleID);
       //this is where it hits an error - it says that vehicleID is not assigned to



I think I'm missing something small and frustrating...

How can I get hold of that variable?
Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Can't assign variable, and access it

#2 bhandari  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 9
  • View blog
  • Posts: 754
  • Joined: 31-January 08

Re: Can't assign variable, and access it

Posted 28 February 2008 - 07:37 AM

Quote

string vehicleID;


use

string vehicleID = "";


Was This Post Helpful? 0
  • +
  • -

#3 Footsie  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 370
  • Joined: 20-September 07

Re: Can't assign variable, and access it

Posted 28 February 2008 - 07:56 AM

Oh good grief that was so simple!

Thanks bhandari.
Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5776
  • View blog
  • Posts: 12,587
  • Joined: 16-October 07

Re: Can't assign variable, and access it

Posted 28 February 2008 - 07:57 AM

Code looks fine, except for two things. First is your error, or probably warning. The message simply means that vehicleID may logically never have anything assigned to it. I'd prefer assigning null, string vehicleID = null; for the simple reason that explicitly tells us nothing was returned.

The other thing, you're only expecting one value? Use an if instead of a while to make that clear. Even better, with the example you have, use ExecuteScalar. e.g.

// set up a default value
int vehicle = -1;
try {
	com.Connection.Open();
	vehicle = Convert.ToInt32(com.ExecuteScalar());
} catch (Exception exc) {
	lblException.Visible = true;
	lblException.Text = "There is a problem with your connection:  " + exc.ToString();
} finally {
	com.Connection.Close();
}
// if (vehicle == -1), something when horribly wrong.



Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#5 Footsie  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 370
  • Joined: 20-September 07

Re: Can't assign variable, and access it

Posted 28 February 2008 - 08:20 AM

Thanks baavgai.
That does look a whole lot cleaner and more intuitive. I will definitely replace it with an ExecuteScalar(). Sometimes when I get an idea in my head its hard to see the other options. ;)
Just one thing though:
Is it a better option to Convert to an Integer32 vehicle = Convert.ToInt32(com.ExecuteScalar()); as you've done here than converting to Int16 as I did?

EDIT:
I just realized why I didn't use an ExecuteScalar() the first time. The command is a SELECT statement that returns a key value which is an integer. I don't think that an ExecuteScalar() will work here... or am I wrong?

This post has been edited by Footsie: 28 February 2008 - 09:09 AM

Was This Post Helpful? 0
  • +
  • -

#6 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Can't assign variable, and access it

Posted 28 February 2008 - 09:50 AM

If you are only returning a single value from an SQL statement then ExecuteScalar is exactly what you need.
Was This Post Helpful? 0
  • +
  • -

#7 bhandari  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 9
  • View blog
  • Posts: 754
  • Joined: 31-January 08

Re: Can't assign variable, and access it

Posted 28 February 2008 - 09:58 AM

Quote

string vehicleID = null;

Thats dangerous for application as far as i think. May throw exception if not null check is not done.

string vehicleID = "";
will atleast not bring the application down.
Was This Post Helpful? 0
  • +
  • -

#8 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5776
  • View blog
  • Posts: 12,587
  • Joined: 16-October 07

Re: Can't assign variable, and access it

Posted 28 February 2008 - 10:09 AM

View PostFootsie, on 28 Feb, 2008 - 10:20 AM, said:

Is it a better option to Convert to an Integer32 vehicle = Convert.ToInt32(com.ExecuteScalar()); as you've done here than converting to Int16 as I did?


The statement int is shorthand for System.Int32. So Int16 doesn't make much sense, unless you declare it in both places or are intentionally looking to loose precision. As a quick proof, try this:
int i = 5;
Debug.WriteLine(i.GetType().FullName);



View PostFootsie, on 28 Feb, 2008 - 10:20 AM, said:

I just realized why I didn't use an ExecuteScalar() the first time. The command is a SELECT statement that returns a key value which is an integer. I don't think that an ExecuteScalar() will work here... or am I wrong?


The ExecuteScalar returns a value of type "object". Technically, so does the reader, but it offers little convience functions that call Convert for you. e.g. reader.GetString(0); should be identical to Convert.ToString(reader.GetValue(0)); However, the methods like reader.GetInt32 will complain differently if the value doesn't match the datatype. Converting GetValue yourself is often the safer option, since the reader may have a difference idea of the data type it's getting from the data source.
Was This Post Helpful? 0
  • +
  • -

#9 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5776
  • View blog
  • Posts: 12,587
  • Joined: 16-October 07

Re: Can't assign variable, and access it

Posted 28 February 2008 - 10:19 AM

View Postbhandari, on 28 Feb, 2008 - 11:58 AM, said:

string vehicleID = "";
will atleast not bring the application down.


If a null can bring down your application, then your code is very poorly written. Worse, if a empty string passes cleanly through, what subtle ways might if fail later?

Some place up the chain you might end up stating that null is an empty string, but that still forces you to deal with it, rather than safely allowing it to sneak by.

Of course, a null start value is just a preference. However, if you deal with passing many types of objects, handilng non initalized values consistently across all objects has advantages. See the NullObject pattern for an example of why the behavior is considered desirable. As of .NET 2.0, this pattern is implemented natively.
Was This Post Helpful? 0
  • +
  • -

#10 Footsie  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 23
  • View blog
  • Posts: 370
  • Joined: 20-September 07

Re: Can't assign variable, and access it

Posted 28 February 2008 - 12:14 PM

jayman9 Posted Today, on 06:50 PM , said:

If you are only returning a single value from an SQL statement then ExecuteScalar is exactly what you need.
Ok great, I tried the ExecuteScalar and it worked well. I was under the impression that you could only return results of queries such as COUNT with an ExecuteScalar. Just to clarify - If I was returning a single value of say a string, which was a name such as "Allan" then an ExecuteScalar would also work here? Just as long as it is one name and not multiple? I thought that a string would count as multiple values...

baavgai Posted Today, on 07:09 PM , said:

The statement int is shorthand for System.Int32. So Int16 doesn't make much sense, unless you declare it in both places or are intentionally looking to loose precision.

I thought it was the other way around - int being short for Int16!
That's why it's good to discuss these things and work out the kinks I suppose.

Thanks all, for the help and discussion.
Was This Post Helpful? 0
  • +
  • -

#11 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Can't assign variable, and access it

Posted 28 February 2008 - 04:57 PM

View PostFootsie, on 28 Feb, 2008 - 11:14 AM, said:

If I was returning a single value of say a string, which was a name such as "Allan" then an ExecuteScalar would also work here? Just as long as it is one name and not multiple? I thought that a string would count as multiple values...

That is correct, you can return any SQL Data type using the ExecuteScalar method, so long as it is only returning a value from one column in one row. Or it can be used with the aggregate functions like Count, Sum, Max...etc these functions will only return one value for a result.
Was This Post Helpful? 0
  • +
  • -

#12 bhandari  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 9
  • View blog
  • Posts: 754
  • Joined: 31-January 08

Re: Can't assign variable, and access it

Posted 28 February 2008 - 11:42 PM

View Postbaavgai, on 28 Feb, 2008 - 10:49 PM, said:

View Postbhandari, on 28 Feb, 2008 - 11:58 AM, said:

string vehicleID = "";
will atleast not bring the application down.


If a null can bring down your application, then your code is very poorly written. Worse, if a empty string passes cleanly through, what subtle ways might if fail later?

Some place up the chain you might end up stating that null is an empty string, but that still forces you to deal with it, rather than safely allowing it to sneak by.

Of course, a null start value is just a preference. However, if you deal with passing many types of objects, handilng non initalized values consistently across all objects has advantages. See the NullObject pattern for an example of why the behavior is considered desirable. As of .NET 2.0, this pattern is implemented natively.


I completely agree with you on Null Pattern and all. But Strings are such a thing that developers forget to check them against null.
We can't assign a blank string to every object in Java. So null has to be there. But at least for String we have a work around.
And its not that i have initialized a String reference with null then I will be the only coder using that variable, others may be calling my functions to use the same reference and if they don't check Strings against null you know the user will keep on clicking that dumb submit button.

*edit
Oh and by the way, have you carefully read that page on wikipedia??
It also says that avoid using null reference, instead implement Null Interface.
Below is the quoted text from wiki:

Quote

Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), you use an object which implements the expected interface, but whose method body is empty.


Hope i make some sense out of this non-sense :lol:

This post has been edited by bhandari: 28 February 2008 - 11:46 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1