Use GetByteCount for the appropriate encoder-- in this case, ASCII for VarChar and Unicode for NVarChar).
var s = "This is a string";
var len1 = s.Length;
var len2 = System.Text.Encoding.Unicode.GetByteCount(s);
var len3 = System.Text.Encoding.ASCII.GetByteCount(s);
Console.WriteLine("'{0}' has {1} characters and is {2} bytes with Unicode encoding and {3} bytes with ASCII encoding.", s, len1, len2, len3);
Output:
'This is a string' has 16 characters and is 32 bytes with Unicode encoding and 16 bytes with ASCII encoding.
No comments:
Post a Comment