user3308043
user3308043

Reputation: 827

NVarChar to C# Data Types

The database stores nvarchar, I retrieve the information and I'd like to jam it into C# data types without any declarative conversion code.

Can you implicitly convert nvarchar to C# data types? (e.g. nvarchar to int)

Upvotes: 6

Views: 29078

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

Nvarchar is a string, if you want to turn it in to a int you will have to go through some kind of conversion as I could have "Potato" in the column, what int would that map to?

Here is a listing of all of the SQL types and what C# types they map to. So if you want an int in C# without conversion your only option is an int in Sql.

Upvotes: 9

Noctis
Noctis

Reputation: 11783

Not much you can do with it implicitly, other than treating it as a string.

You could use some logic to Parse or better TryParse it if you expect it to be an int.

Have a look at the following

string nvarchar1 = "12";
string nvarchar2 = "1.2";
string nvarchar3 = "hello"; 

var one = int.Parse(nvarchar1); // good 
var two = int.Parse(nvarchar2); // exception
var three = int.Parse(nvarchar3); // exception  

var bone = int.TryParse(nvarchar1,out one); // true
var btwo = int.TryParse(nvarchar2,out one).Dump(); // False, 0
var bthree = int.TryParse(nvarchar3,out one); // False, 0

It all depends on if and how much you trust your input in your database.

Upvotes: 1

Related Questions