Reputation: 312
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?
Upvotes: 9
Views: 2283
Reputation: 127543
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.
Upvotes: 12
Reputation: 2696
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.
Upvotes: 2
Reputation: 221
Zero means that nothing is selected. In case of Open 00001, In case Of Connecting 00010, In case of Open AND Connection 00011 ....
0 0 0 0 0
B F E C O
Open = 1,
Connecting = 2,
Executing = 4,
Fetching = 8,
Broken = 16,
Upvotes: 0