-1

I have this snippet :

public delegate decimal CalculerMoyenneGenerale(decimal a, decimal b);
        Func<decimal, decimal, decimal, decimal> fonc1 = (a, b, c) => (a + b * 2 + c * 2) / 5;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            decimal moyenne1 = decimal.Parse(moy1.Text);
            decimal moyenne2 = decimal.Parse(moy2.Text);
            decimal moyenne3 = decimal.Parse(moy3.Text);
            decimal moyenneBac = decimal.Parse(moybac.Text);
            CalculerMoyenneGenerale calcul;
            decimal moyenneAnnee = fonc1.Invoke(moyenne1, moyenne2, moyenne3);
            calcul = (moyenneAnnee < moyenneBac) ? CalculerSansVightcinq : CalculerAvecVightcinq;
          General.Text = calcul(moyenneAnnee, moyenneBac).ToString();

        }

        public decimal CalculerSansVightcinq(decimal annee, decimal bac)
        {
            return bac;
        }

        public decimal CalculerAvecVightcinq(decimal annee, decimal bac)
        {
            return (bac * 75  + annee * 25 ) / 100;
        }

I have a problem in this line :

 calcul = (moyenneAnnee < moyenneBac) ? CalculerSansVightcinq : CalculerAvecVightcinq;

it didn't accept this ternary expression ( exception of casting). If I change this expression by ìf else statement it works.

  1. Why are the reasons of this exception?
  2. How can i resolve it?
Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
  • 1
    Cast one or both of the delegates in your ternary operator explicitly to (CalculerMoyenneGenerale). [Read here more about the resons.](http://stackoverflow.com/a/6308397/2819245) –  May 16 '14 at 21:57
  • 1
    The reason for the error is that the ternary expression involves two different types, neither of which can be implicitly cast or converted to the other. Conversion of the target to which the result of the ternary expression gets assigned doesn't get evaluated until evaluation of the ternary expression is complete. It's the same problem as something like `int? foo = ( isTrue ? 3 : null ) ;`. At least alternative in the ternary expression needs to be cast appropriately: in my example, either `( isTrue ? (int?) 3 : null )` or `( isTrue ? 3 : (int?) null )` will compile. – Nicholas Carey May 16 '14 at 22:09

1 Answers1

-1

Use calcul = (moyenneAnnee < moyenneBac) ? (CalculerMoyenneGenerale)CalculerSansVightcinq : CalculerAvecVightcinq;

Mike
  • 3,766
  • 3
  • 18
  • 32