Search code examples
c#classdelegatesreturn

Can you print delegate contents?


i have method where i create random number once called from other class. Making delegate and pointing it to that method invokes that method itself and random number is generated. I can't access that method without creating new random number. I want to get that method returned value with delegate. By writing it "Console.WriteLine(some_kind_delegate);" gives me path "Consoleapp8.class+method".

P.S although when i use delegate when comparing his pointed value with other variable answer is correct.

Screenshot in visual studio environment with my comments: https://www.dropbox.com/s/cx6858x5qen7k1p/dayum.PNG?dl=0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    abstract class variklis
    {
        delegate int delegatas();
        static int litrazas;

        static void Main()
        {

            Console.WriteLine("serijinis bloko numeris: " + blokas.serijinis_bloko_numeris());
            Console.WriteLine("variklio tipas: In-line " + blokas.vidus() + " cilindrai");
            Console.WriteLine("stumokliu skaicius: " + stumokliai.stumokliuskaicius);
            Console.WriteLine("stumokliu kodas: " + stumokliai.stumokliu_kodas());
            Console.Write("galimas variklio litrazas siam automobiliui: ");
            int.TryParse(Console.ReadLine(), out litrazas);

            litrazui();
        }

            public static void litrazui()
            {
            string damm;
            delegatas zeta;
            zeta = blokas.litrazas;
            Console.WriteLine(zeta);
            if (zeta() <= litrazas)
            {
                damm = "variklis tinkamas siam automobiliui";
            }
            else
            {
                damm = "variklis netinkamas siam automobiliui";
            }
            Console.WriteLine(damm);
            }
        }
    }

Solution

  • The problem is due to the Console.WriteLine implicitely converting the delegate to a string, which is Consoleapp8.class+method, instead you need to invoke the function be appending parenthesis to the end of it.

    Console.WriteLine(zeta());
    

    And to answer the question in your comment. If you need to store the int that is the return from the delegate you can do apply the same principle from above, by appending parenthesis to invoke the function.

    int number = zeta();