Search code examples
c#valueinjecter

Omu.ValueInjecter: can I map values to an existing object?


I've been using Omu.ValueInjecter for a while now but only to 'inject' values into a newly created object.

    public K MapNew(T source) {

        K target = new K();

        target.InjectFrom(source);

        return target;
    }

The code above works well, mapping values from the source to the newly created target.

However, what I'm trying (and failing to do) is to map values from a source object to an existing target. The code below is similar to the one above with the difference being that I'm not creating a new object.

    public T MapToTarget(T target, K source) {
        return target.InjectFrom(source) as T;
    }

Is this possible? The code above merely returns the target with its properties un-modified.

EDIT

Note, in both cases both source and target objects have the same property names.

NOTE

Thanks to Omu for all the help, much appreciated.


Solution

  • the InjectFrom() method matches the properties with same name and type, so if there are properties that match they will be modified

    with valueinjecter you only inject into existing objects