Type Initialization Exception c# - c#

I looked on another question similar to this but couldn't quite understand what they did to solve the problem.
I am simply passing a value into a public static int:
namespace ModNote
{
public partial class homeScreen : Form
{
public homeScreen()
{
InitializeComponent();
}
private void gamemodButton_Click(object sender, EventArgs e)
{
backgroundProgram.moduleNumber = 1;
this.Hide();
moduleScreen showForm = new moduleScreen();
showForm.Show();
}
and this is where this variable is initialized
namespace ModNote
{
#region // Setting up Variables
public class backgroundProgram
{
public static int moduleNumber;
}
#endregion
}
and here a picture of the error: http://puu.sh/opETJ/fb8152d164.png
Thankyou.
edit: initializing the string array causes this error, any problems with this array being initialized? (moduleArray)
namespace ModNote
{
#region // Setting up Variables
public class backgroundProgram
{
public static int moduleNumber;
public static string[] noteArray;
public static string[] moduleArray = new string[7]
{ File.ReadAllText(#"ModulesFile\CGP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1123M.txt"),
File.ReadAllText(#"ModulesFile\CMP1124M.txt"),
File.ReadAllText(#"ModulesFile\CMP1125M.txt"),
File.ReadAllText(#"ModulesFile\CMP1127M.txt"),
File.ReadAllText(#"ModulesFile\CMP1129M.txt")
};
}
#endregion
}

If the exception is throw here:
public static string[] moduleArray = new string[7]
{ File.ReadAllText(#"ModulesFile\CGP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1123M.txt"),
File.ReadAllText(#"ModulesFile\CMP1124M.txt"),
File.ReadAllText(#"ModulesFile\CMP1125M.txt"),
File.ReadAllText(#"ModulesFile\CMP1127M.txt"),
File.ReadAllText(#"ModulesFile\CMP1129M.txt")
};
Then one of those lines is throwing an exception. There are all sorts of reasons for an exception to be thrown when reading from a file - security, not found, in use, etc.
I would suggest moving that logic to the static constructor so you can debug it to find the immediate problem, then add better error handling.
Another option is to not read all of that data in the static constructor and instead create an Initialize method or something. Exceptions in static constructors are difficult to handle in general.

Related

Exception of type 'System.StackOverflowException' was thrown by WorldServer class

Here is my code WorldServer.cs:
public class JsonData
{
public string header;
public Dictionary<string, string> data = new Dictionary<string, string>();
public int connectionId;
}
namespace Server
{
public class WorldServer
{
private Character character = new Character();
void Test()
{
character.UpdateCharacterState();
}
public void Broadcast()
{
Console.WriteLine("We in Broadcast");
}
}
}
Here is my Character.cs:
public class Character : WorldServer
{
public void UpdateCharacterState()
{
Console.WriteLine("State:");
Broadcast();
}
}
And when i try to run my code i receive the following error:
Exception of type 'System.StackOverflowException' was thrown.
I have one base class WorldServer and one that extends it Character. I have to call from WorldServer class the method UpdateCharacterState and from Character class the Broadcast method which is declared in WorldServer class. Is it possible and how?
Can you tell me where is my mistake and how can i fix it?
Ok, so this will work.... however it's not very good OOP, but I'll leave that up to your journey (and future questions) as you learn how to code.
Anyway...
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var server = new WorldServer();
server.Test();
}
}
public class JsonData
{
public string header;
public Dictionary<string, string> data = new Dictionary<string, string>();
public int connectionId;
}
public class WorldServer
{
private Character character = new Character();
public void Test() {
character.UpdateCharacterState(this);
}
public void Broadcast(){
Console.WriteLine("We in Broadcast");
}
}
public class Character
{
public void UpdateCharacterState(WorldServer server)
{
Console.WriteLine("State:");
server.Broadcast();
}
}
}
I think the takeaway for you is to research classes vs instances and what that actually means. The modified code I've given introduces you to a new concept (potentially) for you known as "dependency injection" which is a good way to reference other object types.... try to limit your use of inheritance as much as possible.
Good luck and keep learning!

Why is the GetServer() method returning null?

today I face an issue with some code I have written and really don't know where I have gone wrong, I'll keep it short and sweet basically the GetServer() method in the Faze class is returning null and I am really not sure why, but I was hoping you guys could help me with that.
I have left a few code snippets below of each class involved in the issue and where its initially called to give you a better idea on where things are going wrong.
Program.cs entry point..
static void Main(string[] args)
{
XmlConfigurator.Configure();
Faze.run();
while (true)
Console.ReadKey();
}
Faze class
public static class Faze
{
private static FazeServer fazeServer;
public static void run()
{
Console.Title = "Loading...";
fazeServer = new FazeServer("");
}
public static FazeServer GetServer()
{
return fazeServer;
}
}
FazeServer class
public sealed class FazeServer
{
private ConsoleWorker consoleWorker;
public FazeServer(string lol)
{
LoadServer();
}
private void LoadServer()
{
consoleWorker = new ConsoleWorker();
classLogger.Info("Server has been loaded.");
}
}
ConsoleWorker class
class ConsoleWorker : IDisposable
{
private readonly Timer consoleWorkerTimer;
private readonly int consoleWorkerInterval;
private static ILog classLogger;
public ConsoleWorker()
{
if (Faze.GetServer() == null)
throw new Exception("Server null..");
consoleWorkerInterval = int.Parse(Faze.GetServer().GetConfig().GetConfigElement("console.worker.interval"));
consoleWorkerTimer = new Timer(TimerElapsed, null, TimeSpan.FromMilliseconds(consoleWorkerInterval), TimeSpan.FromMilliseconds(consoleWorkerInterval));
classLogger = LogManager.GetLogger(typeof(ConsoleWorker));
}
private void TimerElapsed(object timerObject)
{
// Do something...
}
public void Dispose()
{
consoleWorkerTimer.Dispose();
}
}
After following the trace, the code that interrupts it is my null check
if (Faze.GetServer() == null)
throw new Exception("Server null..");
Before I added the if statement the line that caused an exception was
consoleWorkerInterval = int.Parse(Faze.GetServer().GetConfig().GetConfigElement("console.worker.interval"));
Why is GetServer() returning null, can anyone help?
I am after a few beers but in the class 'Faze' you have implemented a static field: 'fazeServer' and did not assign a value to it - therefore it is null.
If you would like to assign a value to 'fazeServer' static field please implement in example a static constructor for the class 'Faze' - in example: '
static Faze() { fazeServer = new FazeServer("whatEverString");}'
and that should solve the NRE.
Regards,
P.Sz.
Class fields are initialized to null by default so your code is the equivalent of:
public static class Faze
{
private static FazeServer fazeServer = null;
public static FazeServer GetServer() => fazeServer;
}
of course, calling GetServer() will return the unchaged value which is null.
If you want to initialize it yourself, use a static constructor:
public static class Faze
{
private static FazeServer fazeServer;
static Faze()
{
fazeServer = new FazeServer("");
}
}
or the field initializer:
public static class Faze
{
private static FazeServer fazeServer = new FazeServer("");
}
So it will be certain that you will get an instance when you call GetServer().
You're calling GetServer() before a value has been set in the fazeServer static variable.
The call stack is as follows:
fazeServer = new FazeServer("");
- LoadServer();
- - consoleWorker = new ConsoleWorker();
- - - if (Faze.GetServer() == null)
Or, in plain English:
fazeServer is set to the return value of new FazeServer()
new FazeServer() internally calls LoadServer()
LoadServer() internally calls new ConsoleWorker()
new ConsoleWorker() internally calls Faze.GetServer()
Faze.GetServer() returns the current value of fazeServer
So the code which sets that static variable is internally trying to read that static variable before it has finished setting it.

Static functions have different static class variables?

This is a followup to a previous question: C# Static event null from within class
I have a class like this:
public class PlaylistModel {
public static event EventHandler PlaylistLoadError;
public static int myInt;
public static void LoadPlaylist()
{
try
{
// do some stuff, simulate exception
throw new InvalidOperationException();
}
catch(InvalidOperationException ex)
{
EventHandler handler = PlaylistLoadError;
if(handler != null)
{
PlaylistLoadError(null, null);
}
}
}
}
Else where in the program, I am setting the PlaylistLoadError EventHandler, like so:
public class MainPage {
public MainPage() {
PlaylistModel.PlaylistLoadError += MyErrorHandler;
PlaylistModel.myInt = 5;
}
public static void MyErrorHandler(object sender, EventArgs e)
{
Debug.WriteLine("There was an error");
}
}
Now, inside of LoadPlaylist, PlaylistLoadError is null and myInt is 0, despite setting them elsewhere. Later, when I create an instance of PlaylistModel, PlaylistLoadError and myInt are the correct values. So my question is this - do static functions of a class somehow access different versions of static class variables? I have checked the memory addresses of the static variables, and they are indeed different depending on if I'm inside of a non-static vs. a static function.
Static variables are static and will remain the same while the program is running unless something is called to change it.
If you want to find out what is happening I would change the field to:
private static int _myInt;
and then add:
public static int myInt
{
get { return _myInt; }
set { _myInt = value; }
}
and then add a break point at on set so you can find out when it is being changed.

C# Curly brackets issue

I'm following a tutorial on C# on making a text-based game and I ran into an issue right at the start. The following code:
namespace GameV2
{
class Level
{
private static Room[,] rooms;
#region Properties
public static Room[,] Rooms
{
get { return rooms; }
}
#endregion
public static void Initialize();
*{*
}
private static *BuildLevel*();
{
}
return false;
}
*}*
gives me 3 errors.
Error 1 Invalid token '{' in class, struct, or interface member declaration
Error 2 Expected class, delegate, enum, interface, or struct
Error 3 Type or namespace definition, or end-of-file expected
The italics represent the errors in order. Fr some reason Visual c# express won't let me use { in a method definition, and pushes my final } out of the code box. Any ideas on why this happens?
You don't have semicolons after methods. You may be confusing them for C
method prototypes.
BuildLevel should have a return type.
All statements have to be inside methods, you can only have declarations outside of methods
This should compile:
namespace GameV2
{
class Level
{
private static Room[,] rooms;
#region Properties
public static Room[,] Rooms
{
get { return rooms; }
}
#endregion
public static void Initialize()
{
}
private static bool BuildLevel()
{
return false;
}
}
}
public static void Initialize();
private static *BuildLevel*();
Those are declarations. They cannot be followed by { }. Remove the ; and it will work.
private static TYPEHERE *BuildLevel*();
This is missing a return type.
Remove the two ;
public static void Initialize()
{
}
private static BuildLevel()
{
}
public static void Initialize();
{
}
should be
public static void Initialize()
{
}
Remove the semicolons from the end of your function declarations (before the opening curly brace).
Watch out for the semicolons. You have semicolons between the method names and their bodies.
This may be the problem:
private static *BuildLevel*();
{
}
return false;
You didn't specify a return type, and the return false; should be inside the brackets.

Problem converting array of struct from C++ to C#

I want to convert this C++ code to C#:
typedef struct consoleCommand_s
{
char* cmd ;
void (*function)() ;
} consoleCommand_t ;
static consoleCommand_t commands[] =
{
{"clientlist", &CG__Clientlist},
{"say", &CG_Say},
{"nick", &CG_Nick},
{"logout", &CG_Logout}
} ;
// e.g.
static void CG_Logout(void)
{
// Logout
}
The closest i have come is this:
public class Class1
{
// public delegate int Calculate (int value1, int value2);
public delegate void fnCommand_t();
public class consoleCommand_t
{
public string strCommandName;
public fnCommand_t fnCommand;
public consoleCommand_t(string x, fnCommand_t y)
{
this.strCommandName = x;
this.fnCommand = y;
} // End Constructor
} // End Class consoleCommand_t
public static void Nick()
{
Console.WriteLine("Changing Nick");
} // End Sub
public static void Logout()
{
Console.WriteLine("Logging out");
} // End Sub
// string[] names = new string[] {"Matt", "Joanne", "Robert"};
public consoleCommand_t[] commands = new consoleCommand_t[] {
new consoleCommand_t("Nick", Nick),
new consoleCommand_t("Logout", Logout)
};
} // End Class Class1
Now I wanted to ask:
A) Why does Nick & Logout need to be static when all the rest is not ?
B) Is there no C-like way to initialize the commands array, that is, without new ?
You could do without having a class INSIDE another class and manage your default console commands in another.
public delegate void ConsoleCmd();
public class DefaultCommands
{
public static void Nick()
{
Console.WriteLine("I'm Nick!");
}
public static void LogOut()
{
Console.WriteLine("You're Fired!");
}
}
public class Console
{
private Dictionary<string, ConsoleCmd> mCommands;
public Console()
{
mCommands = new Dictionary<string, ConsoleCmd>();
mCommands.Add("Nick", DefaultCommands.Nick);
mCommands.Add("Logout", DefaultCommands.LogOut);
}
}
Accessing your commands would be as easy as:
ConsoleCmd command = mCommands["Nick"];
command();
EDIT: Failed to mention this. This is to point to the OP that there are other better methods to achieve what he wants to do. And probably doesn't answer his question but I hope will point him to the right direction in terms of his switch from functional programming language to purely object-oriented language.
Nick & Logout may be non-static:
public void Nick(){}
public void Logout(){}
public consoleCommand_t[] commands = new consoleCommand_t[] {
new consoleCommand_t("Nick", this.Nick),
new consoleCommand_t("Logout", this.Logout)
};
B) Is there no C-like way to initialize the commands array, that is, without new ?
Don't get hung up on the new keyword in C#, it's just how initialisation is written. In C#, the analagous distinction between stack allocation and heap allocation is made using struct vs class. (So you might like to make your ConsoleCommand_t a struct.)
Edit: And with a struct you can also do:
new consoleCommand_t() {strCommandName = "Nick", fnCommand = Nick}
And skip writing the consoleCommand_t constructor. That's about as close as you can get to your C-style struct initialization, I think

Categories

Resources