Question

Im trying to get a random number by calling a method (FåKortNummer) in a class but i get an error like in the title that says that my System.Random is a variable but is treated like a method how do i fix this problem

  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace Kortspil
    {
        public class Krig
        {
            public byte FåKortNummer()
            {
                System.Random KortNummer = new System.Random();
                byte kort = KortNummer(1, 11);
                return kort;
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                byte kort = Krig.FåKortNummer();
                Console.WriteLine(kort.ToString());
            }
        }
    }
Was it helpful?

Solution

When you put a pair of parentheses after an expression, you are telling the C# compiler that you would like it to invoke a method. Hence the "used like a 'method'" error.

If you are looking to obtain a random byte, you can do it like this:

byte kort = (byte)KortNummer.Next(1, 11);

This calls the Next method on the KortNummer variable, producing a number from 1 to 11.

OTHER TIPS

You need to use Next method to get a Random number.KortNumber is the name of the Random instance.You can't use it like that:

byte kort = (byte)KortNummer.Next(1, 11);

You are not properly calling the Random class methods to generate Random Numbers.

You need to Call Next() method of Random class to generate Random number

From MSDN: Random.Next()

Returns a random integer that is within a specified range.

this method returns the int value and you need to cast it back to byte as integer can not be implicitly converted to byte.

Try This:

byte kort = Convert.ToByte(KortNummer.Next(1, 11));

You need to make it static so you don't have to instantiate the Krig class, second, make the System.Random a static variable, this way when you call the method in a loop you won't get the same number everytime. Third, you need to call the random.Next Method.

private static System.Random KortNummer = new System.Random();
public static byte FåKortNummer()
{
    byte kort = (byte)KortNummer.Next(1, 11);
    return kort;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top