开发者

Difference between (string)reader[0] and reader[0].ToString()

开发者 https://www.devze.com 2023-03-05 04:13 出处:网络
Is there a difference between DataReader[0].ToString() and (string)D开发者_如何学GoataReader[0]?

Is there a difference between DataReader[0].ToString() and (string)D开发者_如何学GoataReader[0]?

My guess is that (string)DataReader[0] might fail if the database type isn't a string type, where DataReader[0].ToString() would just convert anything outside of a DB null to a string. Is that the case?

Which would be faster?


Those both introduce you to potential data exceptions, IMO the optimal way to read from a reader is:

var x = reader[0] as string

Then for numbers / bools etc I always use nullable types so you can get

var y = reader[1] as int?

Now if you absolutely are as opposed to nullables for some reason (I think they're great for knowing whether something is or not set)

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


(string)DataReader[0] is typecasting. The compiler will insert some set of instructions at compile time that needs to be executed in order to perform the conversion and throws an exception when it fails to do so.

DataReader[0].tostring() is function call which gets resolved at runtime and no exceptions.

Experts please correct me if I am wrong.


I know its too late to comment on this question but I think many people have the similar doubt about (string)object and object.ToString() and this question is the correct place to comment on.

When its sure that the type of object is string then its better to do a typecasting rather than calling a method .ToString(). If you look into the code of ToString() :

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

Which is first finding the type of object by calling GetType() method then calling the ToString() of that type.

If we are not sure about the type of object then the answer would be do ToString() instead of (string).

If you wanted to see the benchmark of performance of (string) vs .ToString() then follow the link : (string) vs .ToString()

0

精彩评论

暂无评论...
验证码 换一张
取 消