Why does the method greet(); returns 0 after 5? :/

Updated on June 10, 2018 in  [G] Say Hello!
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on June 9, 2018

using System;

namespace Methods
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            int res;
            res = greet();
            Console.WriteLine(res);

        }
        public static int greet()
        {
            int obj = new int();
            Console.WriteLine(5);
            return obj;

        }
    }
}

  • Liked by
Reply
1 on June 9, 2018

Because you return obj, and obj is only ever set to a new int. All 5 is doing is being printed to the screen.

If you wanted greet() to return 5, it should be more like:

public static int greet()
{
    int obj = 5;
    Console.WriteLines(obj); // <-- this isn't necessary, but i just wanted to keep my code looking like yours
     return obj;
}

 

on June 10, 2018

thank you for your explanation!! 😀

Show more replies
  • Liked by
Reply
Cancel