Jump to content

C# Methods doubt.

- - - - -

  • Please log in to reply
3 replies to this topic

#1
gautham

gautham

    Learning Programmer

  • Members
  • PipPipPip
  • 33 posts
namespace ConsoleApplication18

{

    class Program

    {

        public Program()

        {

            Console.WriteLine("hi");

        }


        static void Main(string[] args)

        {

            Program p1 = new Program();

        }

    }

}

====

When i am running the above code then it is displaying the message:

Quote

hi
---------------------------

namespace ConsoleApplication11

{

    class program

    {

        public hi()

        {

            Console.WriteLine("Hi");

        }

        static void Main(string[] args)

        {

            program k = new program();

        }

    }

}




but when i am running the above program considering the first example then it is displaying the following error:

Method must have a return type
====


Can anyone explain in detail?


Thank you.

#2
TheCompBoy

TheCompBoy

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 272 posts
What you did at the first example was creating an "Constructor" for the class called "program" and when you created a new instance of the class "program" it always calls the Constructor of the class.

Whats wrong in the second example is that you create the method called hi instead and a method needs to have a type (Example: Void, Int or bool) That's what causing the error.
You could rename the class into "hi" and also change this line:
 program k = new program();

Into this line:
 hi k = new hi();


And then the code in your second example would print out "Hi"
I found this guide that explains what a constructor is since i realy don't know how to explain: How to use C# Constructors

Edited by TheCompBoy, 17 January 2012 - 11:56 AM.

Think my post we're usefull? Please take your time and press the Like button at my post, Big Thanks!
For great C# & Android tutorials visit my blogg: http://www.thecompboy.com/

#3
lespauled

lespauled

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 231 posts
  • Programming Language:C, C++, C#, JavaScript, PL/SQL, Delphi/Object Pascal, Visual Basic .NET, Pascal, Transact-SQL, Bash
A constructor uses the name of the class as its header.

So, you created a class: program

the constructor should be: public program()

The constructor is the same name as the class. Hi, becomes a method of that class. Methods must have a return type.

So, the following would actually work

class program
{
public void hi()
{
Console.WriteLine("Hi");
}
static void Main(string[] args)
{
program k = new program();
k.hi();

Console.Read();
}
}

#4
gautham

gautham

    Learning Programmer

  • Members
  • PipPipPip
  • 33 posts
Thank you TheCompBoy and lespauled.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users