What in the Cast, is different
This question already has an answer here:
The first ( command.ExecuteScalar() as string;
)will do a runtime attempt to convert the result of ExecuteScalar()
into a string. If the resulting type is not a string
, you will receive null
. The as keyword also only performs reference conversions, nullable conversions, and boxing conversions, so you can't use it directly with non nullable value types.
The second ( (string)command.ExecuteScalar();
) will do a conversion to string
directly, and raise an InvalidCastException
if the resulting value is not a string
.
Is one better than another (Performance)?
In general, using the second option should provide (insignificantly) better performance if you know the result is always going to be a string.
Is it just a matter of preference, code legibility?
This is where I make the stronger differentiation. Using as
suggests that the result may not be a string, and you will be handling the null
check. Using a direct cast suggests that you know it's always a string, and anything else is an error and should raise an exception.
In my opinion, this should be the deciding factor for which to choose, since it shows your intent directly in the code.
(string)command.ExecuteScalar()
will throw an exception if command.ExecuteScalar()
cannot be cast.
command.ExecuteScalar() as string
will just return null instead.
上一篇: AS运算符在C#中的用处
下一篇: 演员中的内容与众不同