0
using System;

namespace ConsoleApplication
{
    class Program
    {
        public delegate void mydel(int z);

        static void Main(string[] args)
        {
            Program p = new Program();

            Random r = new Random();
            int k = r.Next(99);

            mydel f;

            if (k > 50)
            {
                f = new mydel(p.high);
            }

            if (k < 50)
            {
                f = new mydel(p.low);
            }

            //f(k) is underlined and Use of unassigned local variable 'f'     
            f(k);
        }

        //methods
        public void high(int m)
        {
            Console.WriteLine("{0}>50", m);
        }

        public void low(int n)
        {
            Console.WriteLine("{0}<50", n);
        }
    }
}

I expected f(k) to work because I gave parameter to delegate. Why am I getting this error? (Use of unassigned local variable 'f' on f(k) portion)

Backs
  • 24,430
  • 5
  • 58
  • 85
Lyrk
  • 1,936
  • 4
  • 26
  • 48

2 Answers2

2

Just add null

mydel f = null

Or put else between conditions. Because, when k == 50 f is not initialized:

    mydel f;

    if (k > 50)
    {
        f = new mydel(p.high);
    }
    else
    {
        f = new mydel(p.low);
    }
Backs
  • 24,430
  • 5
  • 58
  • 85
  • Does compiler check whether I covered all possibilities in if else blocks or not in compile time? – Lyrk Oct 08 '15 at 12:00
  • 1
    @Lyrk it checks that variable is initialized. it's equal to `mydel f = k > 50 ? new mydel(p.high) : new mydel(p.low);` so variable is assigned – Backs Oct 08 '15 at 12:05
2

if k > 50 then f is some delegate, if k < 50 - too. What if k == 50? f is not specified (even it is not null) in that case - so you can't use it.

Quick fix:

mydel f = null;

But you will get NullReferenceException when k == 50; You can also add additional if for case when k == 50;

pwas
  • 3,225
  • 18
  • 40