Varchar() datatype and C# SqlDataReader truncates string

TableDef

When I try and read into my C# program using an SQLDataReader, the Discrepency field above defined above as varchar(512) gets truncated to 255 characters.

I verified that the ColumnSize is 512 with the following C# code:

SqlDataReader = dr2 = cmd2.ExecuteReader();
using (var schemaTable = dr2.GetSchemaTable())
{
    foreach (DataRow row in schemaTable.Rows)
    {
        string ColumnName = row.Field<string>("ColumnName");
        string DataTypeName = row.Field<string>("DataTypeName");
        short NumericPrecision = row.Field<short>("NumericPrecision");
        short NumericScale = row.Field<short>("NumericScale");
        int ColumnSize = row.Field<int>("ColumnSize");
        Console.WriteLine("Column: {0} Type: {1} Precision: {2} Scale: {3} ColumnSize {4}",
        ColumnName, DataTypeName, NumericPrecision, NumericScale, ColumnSize);
    }
}

Any ideas as to why it gets truncated?

I have a vague recollection that all string data in .Net languages is Unicode, which uses 2 bytes per character. So my wild guess is that even though it's declared varchar (1 byte per character), somehow it's getting interpreted and is reading 2 bytes per character. The length is still correct, but the character representation is getting messed up.

What version of C#/.Net are you using?

1 Like

Visual Studio 2022.

Thanks, I will look into that and see what I can find.

Thanks for the suggestion. That was not what turned out to be the problem. You helped me to scrutinize my code a little closer and I found out that it was actually my SQL Stored procedure for updating the table that had the wrong size for the varchar for that field.