TryGetValue - pass uninitialized value OK?

Take the following code to expose A:

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

The documentation for the dictionary says that if the key is not found, the link type will be null. Ok, that's fine.

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

Or, to set the location for the outgoing object to be located, you should set the call as exhibit B:

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

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

(My question comes from my disgust with null pointers in C programming days.)

+5
source share
2 answers

In my opinion, it is better not to set the value. In the end, this value is guaranteed to be replaced by a method call (assuming it throws an exception), so why bother with specifying a value that is meaningless? It simply misleads the reader into thinking that it matters.

The out parameter is different in that the variable you use to provide a value for it does not have to be assigned before the call, but it will definitely be assigned after the call. Any value that it has before the call will not be visible to the method.

(Note that ref parameters do not behave this way - they must be assigned in advance.)

For more information on the various parameter modes in C #, see my article on the C # argument .

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

The parameter value in the method becomes the value of the variable in the caller code in the same way as the normal assignment. No cloning objects.

+8
source

If the key is found, how is the 'sql' variable populated?

You can think like this:

 var sql = GetQueries[type.TypeHandle]; 

Or, to set the location for the outgoing object to be located, you should set the call as exhibit B:

No, it really doesn't matter. You do not need to initialize sql to a value, as you pass it as an out argument. The function ensures that it sets the value of this argument by declaring it as out .

0
source

Source: https://habr.com/ru/post/1203403/


All Articles