Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Casting and Conversion for C# (or, Schrödinger's Data Type)

This may be a basic C# question, but I'm comming from a C/C++ background.

I have an application I'm writing that takes a single date value from a Sql Server database. The problem I'm having is that when the database reads the data via the sqlcommand reader, I get an error stating:

"Unable to cast object of type 'System.DateTime' to type 'System.String'"

Oddly enough, GetString(0) seems to be returning a DateTime during runtime.

However, I'm not able to cast the expression as a DateTime, as far as I know. How can I get the DateTime object out of the expression, or convert this expression to a c# string? Here is my code:

static public string GetSqlString(string SQLText) 
{
    string result = "";
    SqlDataReader reader;

    SqlConnection connection = new SqlConnection("Data Source=DEVDB\\SQLEXPRESS;" +
                                       "Initial Catalog=TestDB;" +
                                       "Trusted_Connection=Yes;");
    using (connection) {
        SqlCommand sqlcommand = connection.CreateCommand();
        sqlcommand.CommandText = SQLText;
        connection.Open();
        reader = sqlcommand.ExecuteReader();
        if (reader != null)
            if (reader.Read())
            {
                // Code breaks on this Line
                result = reader.GetString(0);
                //////////////////////////////////////////////////////
                // This doesn't seem to work either:
                result = (DateTime)(reader.GetString(0)).ToShortDateString;
                // Visual Studio states that this reader.GetString is a string,
                // oddly enough...
            }
            else
            {
                // Purposely Bogus Value
                result = "01/01/1920";
            }
        connection.Close();
    }
    return result;
}


static public DateTime GetCurrentDateDB()
{
    string dateString;
    dateString = GetSqlString("SELECT [ViewingDate] FROM [TestDB].[dbo].[AppGlobals] as varchar");
    DateTime ComputedDate = DateTime.Parse(dateString); 
    return ComputedDate;
}

The results of my query, from SQL Server Managment Studio:

ViewingDate
2010-05-17 00:00:00.000

like image 283
Albert Perrien Avatar asked Jun 04 '26 23:06

Albert Perrien


1 Answers

GetString is a type safe way of getting a column you know is a string.

Use GetValue(0) to get an object you can cast to whatever you need.

Use GetValue(0).ToString() if you're just looking for the default string representation.

String.Format("{0:d}", reader.GetValue(0)); is another way to do that.

((DateTime)reader.GetValue(0)).ToShortDateString(); should be exactly the same as the solution others have suggested. The GetDateTime(0) call does the cast for you. That's why you get the error with GetString, because it tries to cast to String.

like image 139
Kevin Stricker Avatar answered Jun 06 '26 12:06

Kevin Stricker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!