I have a simple cast issue in following simple c# method
using System;
using System.Data.SqlTypes;
...
private void method1() {
string s = "TestString";
object o = s;
SqlString t1 = (SqlString) s;
SqlString t2 = (SqlString) o;
}
...
When casting directly from s
(in case of t1), I don't get any error but when casting from o
I get exception:
Specified cast is not valid.
I have same problem converting from object
to all types System.Data.SqlTypes
How can I cast an object
that has string in it to SqlString
?
This is because there is an implicit conversion operator for String to SqlString.
In other words, you are not dealing with a simple built-in cast: designers of SqlString decided to allow you cast strings to SqlString. They didn't do it for Object, hence the error that you are seeing.
To answer your question
private void method1() {
object o = "MyString";
SqlString t1 = o as String
}
if o is not a string, t1 will be null.
Neither of the other answers addresses the question of casting the object reference to the SqlString. If you are certain that the object reference points to a string, it's simple:
var ss = (SqlString)(string)o;
If o might hold a value other than a string, you can do this, instead:
var ss = (SqlString)(o as string);
Or, if you want to go down the (dangerous) path of storing non-string data in string format:
var ss = o == null ? (SqlString)null : o.ToString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With