If you really wanted the most efficient way to clone a HashSet<T>
, you’d do the following (but possibly at the cost of maintainability)
- Use reflector or the debugger to figure out exactly what fields in
HashSet<T>
need to be copied. You may need to do this recursively for each field. - Use
Reflection.Emit
or use expression trees to generate a method which does the necessary copying of all of the fields. May need to call other generated methods which copy the value of each field. We’re using runtime code generation because it’s the only way to directly access private fields. - Use
FormatterServices.GetUninitializedObject(...)
to instantiate a blank object. Use the method generated in step 2 to copy the original object to the new blank object.