C# C# Basics (Retired) Perform Converting Strings to Integers

Karen Ng
Karen Ng
209 Points

Is it not necessary to include in in body of code, if I instantiate it at the top?

I instantiated 'int runningTotal = 0;' at the top of the code. I also included 'int' before 'runningTotal' in the line 'int runningTotal = int runningTotal + minutes;'

In the solution to this section, the code doesn't include 'int' in the 'int runningTotal = int runningTotal + minutes;' line. Can someone tell me why I don't need to include it? Is it because once you've declared it once ('int runningTotal = 0;') the program remembers and knows you are referring to 'runningTotal'?

''' static void Main() { int runningTotal = 0;

      Console.Write("Enter how many minutes you exercised: ");

      string entry = Console.ReadLine();

      int minutes = int.Parse(entry);        

      // Do I not need to put 'int' before 'runningTotal'? Why?  
      int runningTotal = int runningTotal + minutes; 

      console.WriteLine("You have exercised " + runningTotal + " minutes!");

'''

1 Answer

andren
andren
28,450 Points

You only include the value type of a variable (like int) when you are creating it, when you are referencing or changing an already existing variable you only type it's name, not it's value type followed by it's name.

Every time C# sees a variable with a value type followed by a name it will treat it as you creating a new variable, not referencing an existing one.

Karen Ng
Karen Ng
209 Points

thanks so much, andren!