Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET State of DB Connection

When you manage database connection manually you always open and close it. Sometimes you need to check if connection has some state before do some action. A classic situation is check for not Closed state before close connection. Something like

if (connection.State != ConnectionState.Closed)
    connnection.Close();

As MSDN states the ConnectionState is enum WITH FLAGS. It means that connection state can have different states at same time. May be Broken+Closed or something else...

If you decompile System.Data.ConnectionState enum you will see

[Flags]
public enum ConnectionState
{
    Closed = 0,
    Open = 1,
    Connecting = 2,
    Executing = 4,
    Fetching = 8,
    Broken = 16,
}

The value of Closed item is ZERO. It means that following is always true:

connection.State.HasFlag(ConnectionState.Closed)

So. Any suggestions why does this enum have Flags attribute? Or (if this enum must be Flags) why does Closed item have 0 value?

like image 870
Ivan Avatar asked Feb 18 '16 14:02

Ivan


People also ask

What is connection state in C#?

Describes the current state of the connection to a data source. This enumeration supports a bitwise combination of its member values.

How check connection is closed or not in C#?

Data; if (myConnection != null && myConnection. State == ConnectionState. Closed) { // do something // ... }

What is .NET database connectivity?

So basically, what is database connectivity? In the most simple and easy words, I can say that database connectivity is nothing but an interface, bridge, or a communication medium between your database and your web through which you can manage various applications or functionalities of your web.


2 Answers

I believe in the original .NET 1.1 implementation they planed on making it a flags based enum, However I don't think that is how the current implementation is used if you look at the note in the remarks section

Note:
The values in this enumeration are not designed to be used as a set of flags.

You don't need to check for flags it is safe to do a direct == test. They did not remove the Flags attribute because it would break binary compatibility with .NET 1.1 which they won't do.

like image 79
Scott Chamberlain Avatar answered Sep 28 '22 08:09

Scott Chamberlain


The [Flags] attribute on an enum allows you to assign multiple values to your enum at once, which is not possible otherwise. You can do this with bitwise manipulations, meaning you can store an enum with A and C set (both at once), not just A and not just C.

In this case it may sometime mean that the ConnectionState is Open and Executing.

The value of Closed is assigned zero so that it may not ever mean that the ConnectionState is Closed as well as Open.

This post will provide more clarifications on this matter.

like image 21
Bharat Gupta Avatar answered Sep 28 '22 08:09

Bharat Gupta