In some legacy projects at my work, I see a lot of using statements referring to the dbContext:
using (myContext dal = new myContext())
{
dal.DoSomeDatabaseThing
}
I believe this is fairly standard, and don't see a problem. In many places, however, I see something like this:
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(...)
{
sqlBulkCopy.DestinationTableName = myTable;
sqlBulkCopy.BatchSize = 10000;
}
Lo these many years, I've understood that the object referenced in a using statement is immutable. Indeed, MSDN docs state, "Within the using block, the object is read-only and cannot be modified or reassigned." Nevertheless, code blocks like the one above seem to work just fine.
What am I missing here? Clearly assigning values to an object's properties is modifying the object, no? I spoke to the team lead but he seemed unconcerned -- if it ain't broke, don't fix it -- kind of thing. But, it grates on me!
Any thoughts? Thanks
The specification has this to say about the readonly-ness of the resource acquired in a using statement:
Local variables declared in a resource-acquisition are read-only, and must include an initializer. A compile-time error occurs if the embedded statement attempts to modify these local variables (via assignment or the ++ and -- operators), take the address of them, or pass them as ref or out parameters.
Of note, and as pointed out in the comments, this pertains to the local variable itself, and not the object that it references, which a using
statement likely couldn't make immutable in and of itself without going to some extremes.
Suppose your IDisposable
has a method that, when called, increments a private field to keep track of usages before disposal. The object is clearly mutable, but the mutation is hidden as a side-effect. Should a using
attempt to prevent that? I strongly doubt it. Immutability is not especially easy to achieve in C#, the type must be designed with being immutable in mind. Even marking a field readonly
only effects the field variable- reference types could still be modified through method calls and setting fields or properties.