'Why does this run in Visual Studio 2019 but not 2022? Method in c#
Trying to learn method/functions in c# but this code wont run for some reason, but it do run in visual studio 2019.
Edit: Added the errors I'm getting below
static int ThrowDice(int slag)
{
return ThrowDice(6, slag);
}
static int ThrowDice(int sidor, int slag)
{
int resultat = 0;
Random rnd = new Random();
for (int i = 0; i < slag; i++)
{
int varjekast = rnd.Next(1, sidor + 1);
Console.WriteLine($"kast{i+1} blir {varjekast}");
resultat += varjekast;
}
return resultat;
}
Console.WriteLine("Ange tärningens antal sidor: ");
int sidor = int.Parse(Console.ReadLine());
Console.WriteLine("Ange tärningskast: ");
int kast = int.Parse(Console.ReadLine());
Console.WriteLine("Resultat: " + ThrowDice(sidor, kast));
Console.ReadLine();
Errors im getting:
Severity Code Description Project File Line Suppression State
Error CS1501 No overload for method 'ThrowDice' takes 2 arguments
Severity Code Description Project File Line Suppression State
Error CS8422 A static local function cannot contain a reference to 'this' or 'base'.
Severity Code Description Project File Line Suppression State
Error CS0128 A local variable or function named 'ThrowDice' is already defined in this scope
Severity Code Description Project File Line Suppression State
Error CS1501 No overload for method 'ThrowDice' takes 2 arguments Rollspel2
Solution 1:[1]
As your error message tells you, you can not delcare to local functions with the same name:
Error CS0128 A local variable or function named 'ThrowDice' is already defined in this scope
So you need to name them different or put them in a class like this
Console.WriteLine ("Ange tärningens antal sidor: ");
int sidor = int.Parse (Console.ReadLine ());
Console.WriteLine ("Ange tärningskast: ");
int kast = int.Parse (Console.ReadLine ());
Console.WriteLine ("Resultat: " + new Dice().ThrowDice (sidor, kast));
public class Dice
{
public int ThrowDice (int slag)
{
return ThrowDice (6, slag);
}
public int ThrowDice (int sidor, int slag)
{
int resultat = 0;
Random rnd = new Random ();
for (int i = 0; i < slag; i++)
{
int varjekast = rnd.Next (1, sidor + 1);
Console.WriteLine ($"kast{i + 1} blir {varjekast}");
resultat += varjekast;
}
return resultat;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Johannes Krackowizer |
