Joshua Pearson Joshua Pearson - 7 days ago 5
ASP.NET (C#) Question

Receiving error "use of local unassigned Variable"

The issue here is that when i call variable "game" it returns and unassigned variable compilation error. As i understand it, when I assign the new value to a variable, it is meant to initialize that variable.

public class GameController : Controller
{
// GET: Game
public ActionResult Index()
{
Random rnd = new Random();
int pins = rnd.Next(1, 10);

Games game = new Games()
{
frames = game.frames,
Pins = game.Pins,
Score = game.Score,
player = game.player,
};

return View();
}
}
}


Model

namespace webBowlingProject.Models
{
public class Games
{
public int frames { get; set; }
public int Score { get; set; }
public int Pins { get; set; }
public string player { get; set; }
}
}

Answer

It should be instead

Games game = new Games()
{
    frames = frames,
    Pins = pins,
    Score = Score,
    player = player,
};

That means the first Left hand side variable is the name of the properties of the class and Right hand side variable name is the value you wanted to assign. Now when you say game.frames or game.Pins the problem is that your game which is just initializing (In Process) has no value in the properties of its object

You can also use Visual Studio intellisense in this context. as soon as you put your cursor in between { and } and press CTRL + Enter the list will populate the properties of the class called game. Just select one of them and press tab and then press = and then fill in the value you wanted to assign to that property of your class.

Comments