Question

I'm new to programming, and trying to learn C# for Windows 8 app development. I'm using the book "Head First C# - 3rd Edition." The very first example seems to fail. For those that have the book, this is listed on page 33. In the below code, I've stripped out the unnecessary methods, and only left the relevant code.

public sealed partial class MainPage : Save_the_Humans.Common.LayoutAwarePage
{
    public MainPage()
    {
        Random random = new Random();
        this.InitializeComponent();
    }

    private void startButton_Click(object sender, RoutedEventArgs e)
    {
        AddEnemy();
    }

    private void AddEnemy()
    {
        ContentControl enemy = new ContentControl();
        enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
        AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
        AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
            random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
        playArea.Children.Add(enemy);
    }

    private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
    {
        Storyboard storyBoard = new Storyboard() { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
        DoubleAnimation animation = new DoubleAnimation()
        {
            From = from,
            To = to,
            Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)))
        };
        Storyboard.SetTarget(animation, enemy);
        Storyboard.SetTargetProperty(animation, propertyToAnimate);
        storyBoard.Children.Add(animation);
        storyBoard.Begin();
    }
}

The problem lies in the use of the instantiated field "random." The compile time error says "The Name 'random' does not exist in the current context." I'm not quite proficient enough to know what could be causing the problem.

        AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
            random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
Was it helpful?

Solution

Your random variable is not a field. Change your constructor to this:

private Random random;
public MainPage()
{
    this.random = new Random();
    this.InitializeComponent();
}

OTHER TIPS

That isn't a field; it's a local variable in the constructor.
It doesn't exist outside the constructor.

You need to change it to a field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top