1

I'm in a situation where I could use AutoMapper. But property names on my objects are different and AutoMapper mapping will additional effort for this just one odd usage.

here is my code looks like now

ObjectOne.PropOne = ObjectOne.PropOne.CopyFrom(ObjectTwo.PropX)

Extension method looks like below -

public static T CopyFrom<T, U>(this T target, U source)
{
    bool isValidString = (source is string && source != null && !string.IsNullOrEmpty(source.ToString()));
    bool isValidNonString = (!(source is string) && source != null);

    if (isValidString || isValidNonString)
        target = Utils.GetValue<T>(source);

    return target;
}

is there a way where I can avoid the assignment and can do like below?

ObjectOne.PropOne.CopyFrom(ObjectTwo.PropX)
Xi zu
  • 13
  • 2

1 Answers1

3

You may use:

public static void CopyFrom<T, U>(ref this T target, U source)
{
     bool isValidString = (source is string && source != null && !string.IsNullOrEmpty(source.ToString()));
     bool isValidNonString = (!(source is string) && source != null);

     if (isValidString || isValidNonString)
         target = Utils.GetValue<T>(source);
}

but please note that ref Extension methods are only available in C# 7.2+

NetMage
  • 22,242
  • 2
  • 28
  • 45
Ashkan Mobayen Khiabani
  • 30,915
  • 26
  • 90
  • 147
  • I upvoted this... If the OP is using C# 7.2 could you also update the answer to include null conditional operators and pattern matching? It would look nicer :) – Michael Puckett II Nov 16 '18 at 21:04
  • 1
    @MichaelPuckettII I always like to answer, with minimum changes to OP's code, because it makes the OP fully understand which part of code has problem. when changes are to many, it may confuse the OP. – Ashkan Mobayen Khiabani Nov 16 '18 at 21:14
  • 1
    That's true too! I actually like your way of answering better thinking about it. – Michael Puckett II Nov 16 '18 at 21:14
  • This is great, I totally forgot about `ref`. Unfortunately, I have C# 7.0. From this SO -https://stackoverflow.com/questions/247621/what-are-the-correct-version-numbers-for-c it looks like I should have 7.2 by now as my VS 15.8.1 and .Net framework 4.7.03056 but for some reason I have 7.0 only – Xi zu Nov 16 '18 at 21:43
  • me too but i have to get 7.3 asap – Ashkan Mobayen Khiabani Nov 16 '18 at 21:48