Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryGetValue - pass uninititialized value OK?

Take the following code for exhibit A:

string sql;
if (!GetQueries.TryGetValue(type.TypeHandle, out sql))

Documentation for Dictionary says that if the Key isn't found, the reference type will be set to null. OK, that's fine.

If the key is found, how is the variable 'sql' filled? Is the found value for the key cloned? Is a type of object for the item found created and then the contents of the object copied? Is this safe?

Or, to set up a place for the outbound object to reside, should the call be set up as exhibit B:

var sql = string.Empty;
if (!GetQueries.TryGetValue(type.TypeHandle, out sql))

Then the variable 'sql' is initialized and a safe place for the object exists.

(My question comes from my aversion of null pointers in my C programming days.)

like image 534
Robert Achmann Avatar asked Sep 25 '14 13:09

Robert Achmann


1 Answers

In my view, it's better not to set it to a value. After all, that value is guaranteed to be replaced by the method call (assuming that doesn't throw an exception) so why bother specifying a value which is pointless? It just misleads the reader into thinking it makes a difference.

An out parameter is special in that the variable you use to provide a value for it doesn't have to be definitely-assigned before the call, but will be definitely-assigned after the call. Any value it has before the call will not be visible to the method.

(Note that ref parameters don't behave that way - they have to be definitely assigned beforehand.)

See my article on C# argument passing for more details on the different parameter modes in C#.

If the key is found, how is the variable 'sql' filled? Is the found value for the key cloned? Is a type of object for the item found created and then the contents of the object copied?

The value of the parameter within the method becomes the value of the variable in the callers code, in the same way as normal assignment. There is no object cloning going on.

like image 128
Jon Skeet Avatar answered Nov 07 '22 02:11

Jon Skeet