0

So I have these two methods:

    public static string Figure2D()
    {
        dynamic shapeValue;
        do
        {
            shapeValue = Presentation.Present();
        }
        while (shapeValue.Is3D);
        return shapeValue.ToString("R");
    }

    public static string Figure3D()
    {
        dynamic shapeValue;
        do
        {
            shapeValue = Presentation.Present();
        }
        while (!shapeValue.Is3D);
        return shapeValue.ToString("R");
    }

The only difference between them is the while-condition. How can I merge these two into one function? Passing parameter values is probably necessary & acceptable, but I do like to keep it short. Any ideas?

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
Jesper
  • 2,044
  • 3
  • 21
  • 50

1 Answers1

4

how about

public static string Figure(Predicate<dynamic> p)
    {
        dynamic shapeValue;
        do
        {
            shapeValue = Presentation.Present();
        }
        while (p(shapeValue));
        return shapeValue.ToString("R");
    }
pm100
  • 48,078
  • 23
  • 82
  • 145
  • 2
    I'd suggest `Func` instead of `Predicate` so it can be used simply as `Figure(thing => !thing.Is3D)` – quetzalcoatl May 03 '17 at 22:11
  • Hmm, what is Predicate, and how would I pass the condition? (sorry, kinda new to C#) – Jesper May 03 '17 at 22:11
  • 1
    @Jesper: it's a delegate that returns a bool (as opposed to Func which returns anything you specify). Essentially, Predicate === Func<..., bool>.. For more info, check MSDN or intellisense in VS. – quetzalcoatl May 03 '17 at 22:12
  • @quetzalcoatl sadly dynamic cannot be used in a lambda – pm100 May 03 '17 at 22:13
  • @pm100: `Func f = x => x.Length < 10; Console.WriteLine(f("Hello, World!")); Console.WriteLine(f("Hello"));` tested on https://www.tutorialspoint.com/compile_csharp_online.php --- works, so **dynamic** can be used in lambdas. What did you mean? – quetzalcoatl May 03 '17 at 22:15
  • 1
    @quetzalcoatl but what is the advantage of using `Func` over `Predicate` here? `Predicate` can also be called simply using `Figure(p => p.Is3D)` – degant May 03 '17 at 22:18
  • there are lambda / dynamic rules, maybe you cant define dynamics in lambdas, maybe it depends on c# version? I was bitten by this a few days ago on vs2015 – pm100 May 03 '17 at 22:19
  • @pm100: re: Func-vs-Predicate: no advantage. They are identical. I just noticed bare `Predicate` in the original text, so I suggested using a dynamically-typed version. I wrote `Func` just because I'm more used to it. Since it's identical - one less class name to remember. Stick to what you like more. My point was just that's X instead of just plain X. – quetzalcoatl May 03 '17 at 22:23