0

I am studying subject Delegate in C#. My code below is very basic example but it is giving an null exception error in the line i commented out.

Any suggestion appreciated.

using System;
using System.Collections.Generic;

namespace ConsoleAppCSharpPlayGround
{
    class Program
    {
        static void Main(string[] args)
        {

            BiseylerYap biseyler = new BiseylerYap();

            biseyler.Baskabisey = "baskabisey";

            biseyler.BiseyOldu = new BiseylerYap.BiseyOlduDelegate(OnBiseyOldu);

        }

        static void OnBiseyOldu()
        {
            Console.WriteLine("bisey oldu");
        }

    }

    class BiseylerYap
    {

        public BiseylerYap()
        {

        }

        private string _baskabisey;
        public string Baskabisey
        {
            get
            {
                return _baskabisey;
            }
            set
            {
                BiseyOldu(); // NULL EXCEPTION ERROR OCCURS HERE

                _baskabisey = value;
            }
        }

        public delegate void BiseyOlduDelegate();

        public BiseyOlduDelegate BiseyOldu;

    }


}
CodeNotFound
  • 18,731
  • 6
  • 54
  • 63

1 Answers1

0

You should invert the following two lines:

biseyler.Baskabisey = "baskabisey";
biseyler.BiseyOldu = new BiseylerYap.BiseyOlduDelegate(OnBiseyOldu);

So it becomes:

biseyler.BiseyOldu = new BiseylerYap.BiseyOlduDelegate(OnBiseyOldu);
biseyler.Baskabisey = "baskabisey";

Why because when setting Baskabisey property you need the property BiseyOldu to be not null. If you look at the Baskabisey property setter you are calling like below:

set
{
    BiseyOldu(); 

    _baskabisey = value;
}

A better way is to check that the delegate is not null before calling it:

set
{
    var myVarDelegate = BiseyOldu;
    if(myVarDelegate != null) {
        myVarDelegate(); 
    }

    _baskabisey = value;
}

You need also to look at C# events documentation.

CodeNotFound
  • 18,731
  • 6
  • 54
  • 63