Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatype Datetime value Initialization

Tags:

c#

I am updating the a table with different values and in that one date datatype also there.

After updating the table I am initializing the variables to 0 and spaces based on the datatypes - but I am unable to initialize Datetime Datatype.

How can I do this in C#?

like image 516
Dattu Avatar asked Jun 29 '26 10:06

Dattu


2 Answers

You can get initialize value for every value type by "default" keyword

DateTime a = default(DateTime);
like image 123
Aik Avatar answered Jul 01 '26 22:07

Aik


You can initialize the values to default(type) implicitly - for DateTime: default(DateTime).

For database operations, you would probably be better of with the SqlDateTime type as the minimal or maximal values of DateTime usually cannot be stored in databases as date types.

Initialization:

string connString = "...";
string cmdText = @"INSERT INTO Test(col1, col2) VALUES (@col1, @col2)";
using (SqlConnection conn = new SqlConnection(connString))
{
    using (SqlCommand cmd = new SqlCommand(cmdText, conn))
    {
        cmd.Parameters.Add("@col1", SqlDbType.NVarChar).Value = ""; // or .Value=DBNull.Value;
        cmd.Parameters.Add("@col2", SqlDbType.DateTime).SqlValue = default(SqlDateTime); // or .Value=DBNull.Value;
    }
}

You can initialize all the values to DBNull.Value

like image 45
Jaroslav Jandek Avatar answered Jul 01 '26 23:07

Jaroslav Jandek



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!