Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
The following is one out of many programs i came across in C#. I want to know why we use "Convert.ToInt32(Console.ReadLine());" ?

C#
/*
 * C# Program to Check Whether the Entered Year is a Leap Year or Not
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Program
{
    class leapyear
    {
        static void Main(string[] args)
        {
            leapyear obj = new leapyear();
            obj.readdata();
            obj.leap();
        }
        int y;
        public void readdata()
        {
            Console.WriteLine("Enter the Year in Four Digits : ");
            y = Convert.ToInt32(Console.ReadLine());
        }
        public void leap()
        {
            if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))
            {
                Console.WriteLine("{0} is a Leap Year", y);
            }
            else
            {
                Console.WriteLine("{0} is not a Leap Year", y);
            }
            Console.ReadLine();
        }
    }
}
Posted

Console.ReadLine Method (System)[^] return string value, y is int type, Convert.ToInt32 Method (System)[^] convert this string input to a int value. try to read the documentation and understand
 
Share this answer
 
Comments
Member 12247039 11-Jan-16 5:40am    
Ok . Thanks for the immediate reply.
Console.ReadLine waits until the user has pressed [ENTER] and returns the text the entered before that. Convert.ToInt32 converts text to a number, so passing in Console.ReadLine will convert the year the person has entered "1970" into the number 1970.
 
Share this answer
 
Comments
Member 12247039 11-Jan-16 5:41am    
Ok. I get that now. Thanks for your reply to clear my doubt.
C#
Console.ReadLine()
returns string value but you can't perform any arithmetic operation on string variable so to convert from string to integer we use
C#
Convert.ToInt32(StringValue);
 
Share this answer
 
Comments
Member 12247039 11-Jan-16 5:42am    
Thank you for your reply.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900