Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# strings and VARCHAR and NVARCHAR

Tags:

c#

sql-server

I am curious about how C# interprets/stores different data types coming from SQL Server which are then being stored in a C# string variable:

Example:

Let's say I have a variable to hold a string value retrieved from a database call:

public string TransactionId {get; set;}

Will the value in TransactionId be represented any different if:

  1. The data type in SQL Server was a VARCHAR (8 bits)
  2. The data type in SQL Server was an NVARCHAR (16 bits)

Just wondering how these 2 different data types get stored in the C# string type. Will C# store a VARCHAR value with 8 bits and a NVARCHAR with 16?

like image 473
Slinky Avatar asked Jul 10 '14 12:07

Slinky


2 Answers

They will be stored in the string type pretty much exactly the same. It's only difference is the UTF-16 or larger Formatting in an SQL DB will as you know take up more physical storage space in the DB. If you are using only ASCII/UTF-8 for example (Any 8-bit limited character set) you should store as varchar. the string value in C# will represent exactly the same as nvarchar and varchar are both castable to string natively. The only content difference of your string will be if extended characters are used and stored in nvarchar. These will not store in varchar.

Also just informational; var in a SQL type means the size will dynamically change depending on what content it has been given varchar(n) where n is the max size it can be. works the same with for example, varbinary(n), etc.

like image 197
Skintkingle Avatar answered Oct 22 '22 21:10

Skintkingle


You can have a look here

http://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx

nvarchar and varchar are mapped to String

EDIT: nvarchar, varchar, ntext, text, char, nchar are all mapped to String or Char[]

like image 32
bubi Avatar answered Oct 22 '22 20:10

bubi