Trying to understand what this mean...types(lstTypes[i].AvailableDatatype)

yguyon28
yguyon28 used Ask the Experts™
on
I'm having a hard time understanding this simple line of

 : types(lstTypes[i].AvailableDatatype);

Open in new window



using System;
using System.Collections.Generic;

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

            List<DotNet> lstTypes = new List<DotNet>();
            DotNet bltypes = new DotNet();
            bltypes.AvailableDatatype = "bool";
            lstTypes.Add(bltypes);


            DotNet strTypes = new DotNet();
            strTypes.AvailableDatatype = "string";
            lstTypes.Add(strTypes);

            DotNet intTypes = new DotNet();
            intTypes.AvailableDatatype = "int";
            lstTypes.Add(intTypes);

            DotNet decTypes = new DotNet();
            decTypes.AvailableDatatype = "decimal";
            lstTypes.Add(decTypes);


            types += x =>
            {
                Console.WriteLine(x);
                Console.ReadLine();
            };

            for (int i = 0; i <= lstTypes.Count - 1; i++)
            {
                types(lstTypes[i].AvailableDatatype);
            }




        }

        static event Action<string> types;



    }


    public class DotNet
    {
        public string AvailableDatatype { get; set; }
    }


}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Watch carefully and you will understand it clearly.

If you look for types in the code above, you will notice that there is a static event declared at line number 46.

You will also notice that an inline function is attached to this event at line number between 30-34.

The line you have mentioned simply calls that event handler, which in turn prints the type passed as string.

Here is another implementation which you might be comfortable with:

First define a method which corresponds with the event signature.

        public static void PrintType(String str)
        {
          Console.WriteLine("New implementation " + str);
          Console.ReadLine();
        }

Open in new window


Then simply register it with the event as you would normally do:

types += PrintType;

Open in new window


Then run the code again and notice what happens!
Richard LeeSoftware Enthusiast

Commented:
I would recommend researching the following:

  • Events including Subscribing & Unsubscribing
  • Action & Func
  • Lambda expressions

This, including the answer above will help you understand what is going on.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial