Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3229856
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T16:51:33+00:00 2026-05-17T16:51:33+00:00

I was trying to use a random number generator in a windows forms app,

  • 0

I was trying to use a random number generator in a windows forms app, but I’m having trouble figuring out where to put it. I’m being told “place it in the form constructor” but I don’t think we’re talking the same language. Here’s the code im trying to find a home for:

Random rnd = new Random();
int guessMe = rnd.Next(0,100);

But whenever I try to place it outside of the click even method, it says:

A field initializer cannot reference
the non-static field, method, or
property ‘LAB6B.Form1.r’

So i’m assuming that means what it sounds like; it has to be inside of a static method. But the form constructor doesn’t seem to have any static methods either. Can someone toss me a bone?


Here is the code from the the Form1.cs. Im reading some other tutorial online right now that is saying to do the random number generator in the Form1_Load event, but I’m getting a context/scope error from the button click event.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace LAB6B
    {

        public partial class Form1 : Form
        {


            public Form1()
            {
                InitializeComponent();            

            }

            private void Form1_Load(object sender, EventArgs e)
            {
                Random rnd = new Random();
                int guessMe = rnd.Next(0, 100);
            }

            private void btnEvaluate_Click(object sender, EventArgs e)
            {            
                int totGuesses = 0, myGuess;

                if (txtGuess.Text != "")
                {
                    myGuess = int.Parse(txtGuess.Text);
                    totGuesses++;
                    if (myGuess < guessMe)
                    {
                        btnEvaluate.Visible = false;
                        lblResult.Text = "Too Low!!";
                        lblResult.Visible = true;
                        BackColor = Color.SeaGreen;
                    }
                }

            }
        }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T16:51:34+00:00Added an answer on May 17, 2026 at 4:51 pm

    If you’ve been given that advice, someone is probably suggesting that you declare an instance variable, but initialize it in your constructor. For example:

    public class Foo
    {
        private readonly Random rnd;
    
        public Foo()
        {
            rnd = new Random();
            // Other construction code
        }
    }
    

    Then you can use rnd anywhere in your class.

    This is actually mostly equivalent to:

    public class Foo
    {
        private readonly Random rnd = new Random();
    
        public Foo()
        {
            // Other construction code
        }
    }
    

    … which I mostly prefer, as it shows that the initialization of rnd has nothing to do with any constructor parameters.

    As it seems that part of your difficulty is with the guessMe variable, here’s a more complete version:

    public class Foo
    {
        private readonly Random rnd = new Random();
        private int guessMe;
    
        public Foo()
        {
            guessMe = rng.Next(0, 100);
        }
    }
    

    This is assuming you need guessMe to be an instance variable so you can refer to it throughout the class. On the other hand, perhaps you don’t need the Random variable to be an instance variable – if you’re only generating one random number, it would be better as:

    public class Foo
    {
        private readonly int guessMe;
    
        public Foo()
        {
            Random rnd = new Random();
            guessMe = rnd.Next(0, 100);
        }
    }
    

    However, personally I wouldn’t use either of these approaches. I would use a technique which creates a single instance of Random per thread, to avoid both the perils of Random being non-thread-safe, and the perils of creating two instances of Random very close to each other in time, and ending up with the same seeds.

    I’ve written about this reasonably extensively in an article on my site, including this class:

    using System;
    using System.Threading;
    
    public static class RandomProvider
    {    
        private static int seed = Environment.TickCount;
    
        private static ThreadLocal<Random> randomWrapper =
            new ThreadLocal<Random>(() =>
                new Random(Interlocked.Increment(ref seed))
            );
    
        public static Random GetThreadRandom()
        {
            return randomWrapper.Value;
        }
    }
    

    You can either use RandomProvider directly (calling GetThreadRandom every time you need to generate a random number) or you can pass RandomProvider.GetThreadRandom into your class as a constructor argument for a parameter of type Func<Random> – i.e. inject a dependency of “I want to be able to get an instance of Random at any time”.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Trying to use a guid as a resource id in a rest url but
I've struggled with this all day, I am trying to get a random number
I'm trying out the Rijndael to generate an encrypted license string to use for
Trying to use an excpetion class which could provide location reference for XML parsing,
While trying to use LINQ to SQL I encountered several problems. I have table
I' trying to use a Linq query to find and set the selected value
I trying to use ImageInfo and Jython to get information from a image on
I'm trying to use svnmerge.py to merge some files. Under the hood it uses
I've been trying to use SQLite with the PDO wrapper in PHP with mixed
I'm trying to use SQLBindParameter to prepare my driver for input via SQLPutData .

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.