Is this bad? Creating object without assigning to a variable.
Posted on 2004-10-21
I'm using this code to return a single value from a database.
strVar = New OleDbCommand("SELECT [FIELDNAME] FROM TBLNAME WHERE [CRITERIA]='123', oleCon).ExecuteScalar
This is a very fast, single-line-of-code method of getting what I want. If I were to do this with standard ADO.NET objects, then I'd have to declare a dataadapter, use it to fill a datatable, and then loop through datarows in the datatable just to get the first record returned so I could read from it. That's two to three more variables and a lot more code than one line.
So obviously, the method I'm using is more streamlined... and at this point you may be asking, "So what's the problem?"
Well... my only concern about this method is, I'm basically creating an object (the ole command) and returning one of its methods to a variable (strVar)... but I'm not returning the OBJECT itself to the variable, just its method. So my ole command gets created, but I don't have any control over it after the fact.
My question is... is this bad? Does this leave the oledbcommand object out in memory indefinitely (or until my app shuts down or whatever). Is this bad practice...? Should I be flogged for this? What are the ramifications here?