I am trying to code a card game, and I'm making a shuffling system using a function, however it's telling me I need a closing bracket while all my brackets are closed. It's also asking me for an end-of-file or namespace definition. I'm using an online editor (dotnetfiddle.net) to edit this code, if that changes anything.
Here's my current code-
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
List<string> shuffle(List<string> l) { //ERROR 1: } expected
int count = l.Count-1;
List<string> ret = new List<string>();
int ind = 0;
Random rng = new Random();
string card = null;
while (count > -1) {
ind = rng.Next(0, count);
card = l[ind];
l.RemoveAt(ind);
ret.Add(card);
card = null;
count--;
}
return ret;
}
List<List<string>> playerHands = new List<List<string>>();
//💧🔥🌀🌱 (copypaste symbols)
List<string> deck = new List<string> {"1💧", "2💧", "3💧", "4💧", "5💧", "6💧", "7💧", "8💧", "9💧", "1🔥", "2🔥", "3🔥", "4🔥", "5🔥", "6🔥", "7🔥", "8🔥", "9🔥", "1🌀", "2🌀", "3🌀", "4🌀", "5🌀", "6🌀", "7🌀", "8🌀", "9🌀", "🌱1", "🌱2", "🌱3", "🌱4", "🌱5", "🌱6", "🌱7", "🌱8", "🌱9"};
List<string> sDeck = new List<string> {"R🔄", "S❌", "D🔳", "X⛈", "+✨", "A🌕", "A🌑"};
List<string> vDeck = new List<string> {"V◆", "V◇", "V◈"};
}
}//ERROR 2: Namespace, type, or end-of-file expected
Maybe it is related to the C# version you used.
Local functions are only allowed when using C# 7.
When I pasted your code in VS 2019, the compilation succeeded.
The only warning I have, is related to the function shuffle() that is declared but never used.
Also, always put your class in a namespace.
Related
i am starting to learn C#, my first language i learned is Python and i switched to Visual Studio Code for it from Pycharm.
I am trying to code a simple TicTacToe as exercise, when i loop trough my TicTacToe grid to see if one of the empty fields marked with numbers is still avaliable, i get an unexpected output.
The expected output would be 1-9, but its not, i am not allowed to post images so not sure how to say/show it.
When i use char as data type the correct value seems to be there in '' as second value, but how do access it?
in both cases comparision operator do not yield the expected results!
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace CSharp_Shell
{
public static class Programm
{
static int meow = 1;
static string board_roof = "-------";
static string board_mid1 = "|1|2|3|";
static string board_mid2 = "|4|5|6|";
static string board_mid3 = "|7|8|9|";
static string board_all_default = board_roof + Environment.NewLine + board_mid1 + Environment.NewLine +board_mid2 + Environment.NewLine +board_mid3 + Environment.NewLine + board_roof;
public static void Main(string[] args) {
Acces_board2(meow);
}
public static void Acces_board2(int lfm) {
for(int gas=0; gas<board_all_default.Length; gas++) {
bool result = char.IsNumber(board_all_default[gas]);
if (result) {
Console.WriteLine($"{board_all_default[gas]} , {lfm}");
if(lfm < board_all_default[gas]) {
Console.WriteLine($"True");
}
}
}
}
}
}
doesnt matter if i use
if (lfm < board_all_default[gas])
or
int checkme = board_all_default[gas];
if (lfm < checkme)
it never works, that would be no issue in python, i have no clue whats happening
I'm trying to use the CommandLineParser Library in Version 2.5.0 in a WinForms application.
It works great except for a help screen (MessageBox in that case).
I already figured out that I need to create a own parser and set at least the HelpWriter property to null to create a custom Help Screen.
But when the application is called with --help argument my "Error handler" just get one error instance with a Tag of type CommandLine.ErrorType and a Value of HelpRequestedError
Now how to build the custom Help Screen?
https://github.com/commandlineparser/commandline/wiki/Generating-Help-and-Usage-information
This site suggests to use the Types in CommandLine.Text Namespace but how? There are zero examples how to do it.
Anyone here did something like this?
I have the following code:
namespace myWorkspace
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using CommandLine;
using DevExpress.XtraEditors;
using Options;
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
internal static int Main(string[] args)
{
AppDomain.CurrentDomain.SetupInformation.PrivateBinPath = "bin";
WindowsFormsSettings.EnableFormSkins();
WindowsFormsSettings.EnableMdiFormSkins();
WindowsFormsSettings.ForceDirectXPaint();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var parser = new Parser(config =>
{
config.AutoHelp = true;
config.AutoVersion = true;
config.CaseInsensitiveEnumValues = false;
config.CaseSensitive = false;
config.EnableDashDash = true;
config.HelpWriter = null;
config.IgnoreUnknownArguments = true;
//config.MaximumDisplayWidth
config.ParsingCulture = CultureInfo.InvariantCulture;
});
return Parser.Default.ParseArguments<RunOptions>(args)
.MapResult(
RunRunAndReturnExitCode,
RunParsingFailedAndReturnExitCode);
}
private static int RunRunAndReturnExitCode(RunOptions opts)
{
try
{
Application.Run(new MainForm());
}
catch
{
return -1;
}
return 0;
}
private static int RunParsingFailedAndReturnExitCode(IEnumerable<Error> errs)
{
foreach (var err in errs)
{
var locErr = err;
}
return 1;
}
}
}
And on Line var locErr = err; i don't know what to do to get a help screen message i can show in a MessageBox or the like.
CommandLineParser seems to support console output out-of-the-box for help or --help but I have no console app here.
Ok i now figured out a way to do it. Does not seem to be the best way but it works.
I create a StringBuilder instance and put it into a StringWriter instance
private static StringBuilder helpTextBuilder = new StringBuilder();
private static StringWriter helpTextWriter = new StringWriter(helpTextBuilder);
Then I create a new Parser with (at least this) Option(s):
var parser = new Parser(config =>
{
config.HelpWriter = helpTextWriter;
});
In the case of error I can now use what is written into the helpTextBuilder to show a message box.
private static int RunParsingFailedAndReturnExitCode(IEnumerable<Error> errs)
{
MessageBox.Show(helpTextBuilder.ToString());
return 1;
}
So this is now working for me.
Trying to make a simple app which will ask a few questions.
But for some reason, my AskQuestion function doesn't work.
I plan on adding an easily swap able database later which is why I'm trying to take a slightly more modular approach and as I am a beginner I am unsure what I did wrong. The only errors are in line 21 for the AskQuestion class.
Errors are:
CS1001 Identifier Expected
CS1514 { expected
CS1513 } expected
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Quiz
{
class Program
{
// Question Base
class Question
{
public String question = "Empty Question";
public String correctanswer = "Empty Answer";
public String givenanswer = "Empty Answer";
public String response = "Empty Response.";
public bool cleared = false;
}
// Ask Base
class void AskQuestion(Question Q)
{
while (Q.cleared == false)
{
Console.WriteLine(Q.question);
Q.givenanswer = Console.ReadLine();
Q.givenanswer.ToLower();
if (Q.givenanswer == Q.correctanswer)
{
Console.WriteLine(Q.response);
Q.cleared = true;
}
else
{
Console.WriteLine("Wrong. Try again.");
}
}
}
// Main Function
void Main(string[] args)
{
string Name;
Console.WriteLine("Welcome challenger! You're going to have a good time.");
Console.WriteLine("Make sure you use proper grammar. Or you may be stuck for no reason.");
Console.WriteLine("What is your name challenger?");
Name = Console.ReadLine();
Console.WriteLine("Welcome {0} to the challenge. I wish you best of luck. You will need it.",Name);
Question Q1 = new Question();
Q1.question = "What is the color of the sun?";
Q1.correctanswer = "White";
Q1.response = "Correct. Despite the fact it appears Yellow on earth, if you observe the sun from space, you would see it's true color. White.";
AskQuestion(Q1);
Q1.cleared = true;
Console.WriteLine("Nice little warmup. But, lets get a bit serious.");
}
}
}
change this
class void AskQuestion(Question Q)
to
void AskQuestion(Question Q)
This should be a method. The keyword class tells the compiler you want to create a inner class inside the out class Program
Q.givenanswer.ToLower(); doesn't make Q.givenanswer lowercase - it returns a new lowercase string which you need to assign to a variable, or just `Q.givenanswer = Q.givenanswer.ToLower();
I am trying to run a script to read values from an Excel sheet using EPPlus and load them into a list of tuples.
However when I run the script I am getting two errors, the first is:
An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
I have seen in other posts that I need to check for the inner exception, however none is offered by Visual Studio 15.
This is all the exception details that are available.
System.TypeInitializationException was unhandled
Message: An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
Additional information: The type initializer for 'CGCompare2.Program' threw an exception.
Then when I close the VS15 exception window I get a pop up dialogue:
Cannot access a disposed object.
Object name: 'HwndSourceAdapter'
I am unsure what the issue is, if this is caused by my code or not. Any help, much appreciated.
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using OfficeOpenXml;
namespace CGComparer
{
class Program
{
private static List<Tuple<string, string>> _listTop;
private static List<Tuple<string, string>> _listGNED;
private static Base _baseCell;
private static ExcelPackage _package = new ExcelPackage(new FileInfo(_excelFile));
private static string _excelFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"Compare GNED and TOP V1.0.xlsx");
static void Main(string[] args)
{
_baseCell = new Base(1, 2);
_listTop = ColumnsToList(_baseCell.Column(),_baseCell.Row());
_baseCell = new Base(3, 2);
_listGNED = ColumnsToList(_baseCell.Column(),_baseCell.Row());
}
public static List<Tuple<string, string>> ColumnsToList(int column, int row)
{
var list = new List<Tuple<string, string>>();
var ws = _package.Workbook.Worksheets[1];
var ListIsValid = true;
do
{
var userEmail = (string)ws.Cells[column, row].Value;
var customerGroup = (string)ws.Cells[column + 1, row].Value;
if (!string.IsNullOrEmpty(userEmail))
{
list.Add(new Tuple<string, string>(userEmail, customerGroup));
row = row++;
}
else
{
ListIsValid = false;
}
} while (ListIsValid);
return list;
}
}
}
Base.cs
namespace CGComparer
{
public class Base
{
private static int _column;
private static int _row;
public Base(int column, int row)
{
_column = column;
_row = row;
}
public int Column()
{
return _column;
}
public int Row()
{
return _row;
}
}
}
So, turns out the issue was staring me in the face, I went through below steps provided by, Hans Passant in the issue comments:
"The debugger in VS2015 is a crappy bag 'o bugs, it won't let you look
at the InnerException. Use Tools > Options > Debugging > General >
tick "Use Managed Compatibility Mode" and now you can see it. Careful
with those statics, their initializer can byte you in the rear end
badly."
It was a null reference exception caused by me declaring the excel file with a path argument that had yet to be declared itself.
private static ExcelPackage _package = new ExcelPackage(new FileInfo(_excelFile));
private static string _excelFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"Compare GNED and TOP V1.0.xlsx");
I tring to test a new dll that I've build for c#
private void button1_Click(object sender, EventArgs e)
{
String [] first = UserQuery.Get_All_Users();
//MessageBox.Show(first);
}
but I get the following error at String [] first = UserQuery.Get_All_Users();
An unhandled exception of type 'System.NullReferenceException' occurred in User_Query.dll
Additional information: Object reference not set to an instance of an object.
I been tring to figure this one out for hours but can't find any null varibles
I post my dll in case the dll is wrong
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace User_Query
{
public class UserQuery
{
public static string[] Get_All_Users()
{
string[] names = new string[10];
var path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (var computerEntry = new DirectoryEntry(path))
{
var userNames = from DirectoryEntry childEntry in computerEntry.Children
where childEntry.SchemaClassName == "User"
select childEntry.Name;
byte i = 0;
foreach (var name in userNames)
{
Console.WriteLine(name);
names[i] = name;
i++;
}
return names;
}
}
}
}
There is a problem with your. path variable... since there should be \\ instead of //
The problem here turned out not to be the code but be VS2010 not loading the dll. This happen because I decided to change the program from using the dll from the debug to the release version but I did not clean the project after doing it and therefore the program was not correctly loading the dll. All that need to be done was clean the project