Home > Back-end >  Program that displays your born time
Program that displays your born time

Time:12-15

            Console.WriteLine("What year where you born?");
            int const born_year = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("You were born in this year "   born_year);
            Console.ReadLine();

When I try to add a const to the variable int I get the following errors:enter image description here

CodePudding user response:

A const is a compile-time constant. However Console.ReadLine() surely just returns a value at runtime. So this cannot be done. Delete the const-keyword:

Console.WriteLine("What year where you born?");
int born_year = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You were born in this year "   born_year);
Console.ReadLine();

If you wanted something that can be assigned exactly once similar to JAVAs final, you'd need to create a readonly field in your class that you assign from within a constructor.

CodePudding user response:

First of all, the way you define a constant is const type var_name = <literal>

Here is an example:

const int zero = 0;

Second of all, you can only assign literals and other compile-time values. So only "hand-written" numbers, characters and strings like 1, 2, 3, 'a', 'b', "abc" and so on. So you should omit the const keyword:

Console.WriteLine("What year where you born?");
int born_year = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You were born in this year "   born_year);
Console.ReadLine();
  •  Tags:  
  • c#
  • Related