In the ‘DBUtility’ project of Petshop 4.0,the abstract class SqlHelper has a method ‘GetCachedParameters’:
public static SqlParameter[] GetCachedParameters(string cacheKey) { SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey]; if (cachedParms == null) return null; SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length]; for (int i = 0, j = cachedParms.Length; i < j; i++) clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms; }
why not return the ‘cachedParms’ directly ?
If cachedParms were returned directly, the caller could then change the elements of the array. The contents of the cache would then be effectively corrupted – the next caller to fetch the parameters from the cache with the same cache key would get unexpected results.
EDIT: Cloning the array itself prevents the elements being replaced with different parameters. Cloning the elements as well prevents the parameter objects being mutated. Basically it’s all defensive coding.