tags:

views:

629

answers:

3

In .Net, is there any functional difference between creating a new SqlCommand object and attaching a SqlConnection to it and calling CreateCommand on an existing SqlConnection object?

+6  A: 

No, they are the same thing.

I disassembled SqlConnection.CreateCommand and found this:

public SqlCommand CreateCommand()
{
        return new SqlCommand(null, this);
}

which proves that they really are the same thing.

Andrew Hare
A: 

Functionally they are exactly the same.

However, SqlConnection.CreateCommand lets you be more agnostic about what type of DB you are using. For example instead of passing a SqlConnection instance around you could pass it around as a DbConnection which would yield a DbCommand.

JohannesH
+2  A: 

They do the same thing. The rationale behind SqlConnection.CreateCommand is to implement the factory pattern.

Mehrdad Afshari