Is a cast to string always possible without exception?

G

geronimi

I wonder when an exception raises when I do this:

string str= (string)ds.Tables[0].Rows[0]["CODE"]

The row is always filled with data

If there is a dbnull.value in it, does it raises an error?
And for other data?

thx
 
J

Jon Skeet [C# MVP]

geronimi said:
I wonder when an exception raises when I do this:

string str= (string)ds.Tables[0].Rows[0]["CODE"]

The row is always filled with data

If there is a dbnull.value in it, does it raises an error?
Yes.

And for other data?

If the value isn't a string, you'll get an exception.

Jon
 
G

geronimi

So an integer or object will fail? I thought it will make from a 7 a
"7"

If I do string str=Convert.ToString(ds.Tables[0].Rows[0]["CODE"] )
in stead of string str= (string)ds.Tables[0].Rows[0]["CODE"]

does that make any difference?
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


geronimi said:
I wonder when an exception raises when I do this:

Whenever the content if not a string or a type that define an explicit
conversion. They are not that much though.

string str= (string)ds.Tables[0].Rows[0]["CODE"]

The row is always filled with data

What kind of data?
If there is a dbnull.value in it, does it raises an error?

YES
try this:
string s = (string) DBNull.Value;
And for other data?

See the first answer, the safest way is first to test for null and assign if
not.
 
J

Jon Skeet [C# MVP]

geronimi said:
So an integer or object will fail? I thought it will make from a 7 a
"7"

Not with a cast, no.
If I do string str=Convert.ToString(ds.Tables[0].Rows[0]["CODE"] )
in stead of string str= (string)ds.Tables[0].Rows[0]["CODE"]

does that make any difference?

Yes, that should be fine. Or just call ToString().

Jon
 
S

Stoitcho Goutsev \(100\)

geronimi,

No, that will throw exception if the object is not a string.

You can always use ToString() thought. It will never throw an exception.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top