Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception When Casting String Object to SqlString

Tags:

c#

types

casting

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?

like image 356
Bistro Avatar asked Jan 27 '12 03:01

Bistro


3 Answers

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.

like image 101
Sergey Kalinichenko Avatar answered Nov 18 '22 18:11

Sergey Kalinichenko


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.

like image 20
SynXsiS Avatar answered Nov 18 '22 18:11

SynXsiS


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();
like image 31
phoog Avatar answered Nov 18 '22 17:11

phoog