The difference between the (string) reader [0] and the reader [0] .ToString ()

Is there any difference between DataReader[0].ToString()and (string)DataReader[0]?

My assumption is that it (string)DataReader[0]might fail if the database type is not a string type, where it DataReader[0].ToString()will simply convert anything outside the database zero to a string. Is this the case?

What will be faster?

+3
source share
3 answers

Those who introduce you to potential data exceptions, IMO, the best way to read from the reader:

var x = reader[0] as string

Then for numbers / bools etc. I always use types with a null value, so you can get

var y = reader[1] as int?

, - nullables ( , , - )

int i = (reader[1] as int?).GetValueOrDefault()

+2

() DataReader [0] . , , , .

DataReader [0].tostring() - , .

, , , .

0

, , , (string)object object.ToString(), .

, , typecasting .ToString(). ToString():

    public virtual string ToString()
    {
      return this.GetType().ToString();
    }

, GetType(), ToString() .

If we are not sure about the type object, then the answer will be ToString()instead (string).

If you want to see the performance benchmark (string) vs .ToString (), go to: (string) vs .ToString ()

0
source

All Articles