Results 1 to 14 of 14

Thread: Conversion Question

Threaded View

  1. #1

    Thread Starter
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,110

    Conversion Question

    I haven't done much with C#, but this just seems odd to me, so I figured I'd ask to see what is going on.

    I have a datareader that gets one field from a database. That field is usually a string, but in one case, I'm looking for an integer field.

    I had this line:
    Code:
    New SelectedListItem(dr[0].ToString(),dr[0].ToString())
    that worked fine, as there is a form of the constructor that takes two strings as arguments. However, I then realized that I needed to do something slightly different in one highly specialized case, so I wrote this line:

    Code:
    string st1 = dr[0].ToString();
    This gives a warning because dr[0] could be null. It can't actually, because that line is inside the else case where I do something different if dr[0] is null, but that's unimportant.

    My first question is why is it fine to use the code as an argument to a constructor that takes a string (but not a nullable string, as far as I can see), but it isn't okay to assign it to a string variable? Is the constructor assuming that it's arguments might just be nullable? Why wouldn't the argument be string? in that case?

    Anyways, I then tried to do this:

    Code:
    string st1 =dr.GetString(0);
    but that doesn't work because dr[0] is not always a string. In that one case, it is an integer, so GetString() throws an exception.

    So, my second question is: There must be some easy way to solve this, though I'm not seeing it, and I'm not quite sure how to put it in the form of a searchable question. So, what am I missing?
    Last edited by Shaggy Hiker; Mar 21st, 2024 at 03:59 PM. Reason: Fixed the title.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width