views:

83

answers:

2

.NET I want to clone a value type's fields. How can i set a field value on a value type using reflection (or something else dynamically)?

This works for reference types but not for value types. I understand why but I don't know an alternative.

shared function clone(of t)(original as t) as t
  dim cloned as t

  'if class then execute parameterless constructor
  if getType(t).isClass then cloned = reflector.construct(of t)()

  dim public_fields = original.getType.getFields()

  for each field in public_fields
     dim original_value = field.getValue(original)
     'this won't work for value type, but it does work for reference type ???
     field.setValue(cloned, original_value)
  next

  return cloned
end function
A: 

Since value types are passed by value, SetValue is being called on a copy of the object.

If T is a value type, you can simply write Return original and it will return a copy.
For example:

If GetType(T).IsValueType Then Return original
SLaks
+1  A: 

If it is a value type then you are done quick, just return "original":

'if class then execute parameterless constructor
If GetType(t).IsClass Then
  Dim types(-1) As Type
  cloned = DirectCast(GetType(t).GetConstructor(types).Invoke(Nothing), t)
Else
  Return original
End If

You'll have more trouble making this truly universal, a type doesn't have to have a parameter-less constructor. Try a String for example.

Hans Passant
thanks i'm an idiot
soccerazy