Q:

C# error with a declared variable in an if statement

I'm new to coding. I'm taking a C# class and am trying to code a app in Visual Studio. In the image below on line 45 is the error: Use of unassigned local variable "caloriesFromFat". I have declared it and on line 37 I assigned it a value with: "caloriesFromFat = fatGrams * fatGram_Rate;"
How do I solve this. I know it should be simple, but I do not know and have not found an answer yet.
Thank you for any help.

A:

You will need to give caloriesFromFat a value when initiating or at least before trying to access its value on line 45. In your code it is conditional if the variable caloriesFromFat is assigned or not. For your exact problem, you'll need to do something like this while creating the variable.
double fatGrams, totalCalories, caloriesFromFat = 0, percentCaloriesFromFat;

Additionally while taking a look at your code, it seems that something is wrong with your code logic, but this is only a vague guess on the first look at your code.

