I have some code that produces this compiler error:
CS0236 A field initializer cannot reference the non-static field, method, or property 'PublicModule.rnd'
The code is below, with the line with the error marked:
public class PublicModule : ModuleBase
{
Random rnd = new Random();
int value = rnd.Next(4,50); // <<<< Error is here
[Command("Ping")]
public async Task ping()
{
await ReplyAsync(Context.User.Mention + ", Pong!");
}
[Command("Hara")]
public async Task hara()
{
await ReplyAsync("Hara noi te iubim <3 .");
}
[Command("kek")]
public async Task kek()
{
await ReplyAsync(Context.User.Mention + ", kek");
}
[Command("Random")]
public async Task Dice()
{
await ReplyAsync(Context.User.Mention + " ur random number is : " + value);
}
}
How can I call that rnd.Next
from a class? I'm noob at coding and I don't know how can I call things from another class or function etc.
Put it in the constructor:
But I should also point out that this will only give you a new random number once per class instance. If you want a different random number every time you call the function, you should do it like this:
Remove the statement
int value = rnd.Next();
from the class and move it to the functionDick()
as follows:Hope it helps.