C
C#

help

ArgumentNullException when argument is not null

BBujju10/9/2022
I have this code:
public class Config
{
[JsonProperty("token")]
public string Token = "TOKEN HERE";

[JsonProperty("source_url")]
public string SourceUrl = "SOURCE URL HERE";

[JsonProperty("server_url")]
public string ServerUrl = "SERVER URL HERE";

[JsonProperty("invite_url")]
public string InviteUrl = "INVITE URL HERE";

[JsonIgnore]
private string _fileName;

public Config(string fileName)
{
_fileName = fileName;

if (!File.Exists(_fileName)) File.Create(_fileName).Close();

var loaded = JsonConvert.DeserializeObject<Config>(File.ReadAllText(_fileName));
if (loaded is not null)
{
Token = loaded.Token;
SourceUrl = loaded.SourceUrl;
ServerUrl = loaded.ServerUrl;
InviteUrl = loaded.InviteUrl;
}
else
{
File.WriteAllText(_fileName, JsonConvert.SerializeObject(new Config(), Formatting.Indented));
}
}

private Config()
{
_fileName = string.Empty;
}

public void Update()
{
File.WriteAllText(_fileName, JsonConvert.SerializeObject(this, Formatting.Indented));
}
}
public class Config
{
[JsonProperty("token")]
public string Token = "TOKEN HERE";

[JsonProperty("source_url")]
public string SourceUrl = "SOURCE URL HERE";

[JsonProperty("server_url")]
public string ServerUrl = "SERVER URL HERE";

[JsonProperty("invite_url")]
public string InviteUrl = "INVITE URL HERE";

[JsonIgnore]
private string _fileName;

public Config(string fileName)
{
_fileName = fileName;

if (!File.Exists(_fileName)) File.Create(_fileName).Close();

var loaded = JsonConvert.DeserializeObject<Config>(File.ReadAllText(_fileName));
if (loaded is not null)
{
Token = loaded.Token;
SourceUrl = loaded.SourceUrl;
ServerUrl = loaded.ServerUrl;
InviteUrl = loaded.InviteUrl;
}
else
{
File.WriteAllText(_fileName, JsonConvert.SerializeObject(new Config(), Formatting.Indented));
}
}

private Config()
{
_fileName = string.Empty;
}

public void Update()
{
File.WriteAllText(_fileName, JsonConvert.SerializeObject(this, Formatting.Indented));
}
}
And whenever I try to access the following field, I get the following exception:
private static Config Config = new("config.json");
private static Config Config = new("config.json");
System.TypeInitializationException: 'The type initializer for 'class' threw an exception.'

Inner Exception:
ArgumentNullException: Path cannot be null. (Parameter 'path')
System.TypeInitializationException: 'The type initializer for 'class' threw an exception.'

Inner Exception:
ArgumentNullException: Path cannot be null. (Parameter 'path')
AAnton10/9/2022
which line does it get thrown at? in the constructor
BBujju10/9/2022
How do I see that?
AAnton10/9/2022
the debugger should show you try instantiating the config in normal flow, like in the main method, if it doesn't show the line the fact that it's statically initialized like that might be confusing it
BBujju10/9/2022
It's at File.Create(_fileName).Close();
AAnton10/9/2022
but in general, reading files in a constructor that's called in static context might not be the best idea
BBujju10/9/2022
When I hover over _fileName, it says it isn't null, but that's where it throws the exception
AAnton10/9/2022
a constructor reading files is already cursed to me
BBujju10/9/2022
So I should move it to a method?
AAnton10/9/2022
absolutely that however is not the problem here you sure it doesn't fail on the second line? where you deserialize ah hold on when deserializing it calls the constructor again probably with a null argument
BBujju10/9/2022
It's a different constructer
AAnton10/9/2022
which is absolutely cursed you sure it calls private constructirs by default?
BBujju10/9/2022
That's the only parameterless constructer
AAnton10/9/2022
it bet it favors public ones if there are any and tries to match parameters by name or passes nulls try making it public it might actually just work
BBujju10/9/2022
Oh wait it works now without making it public By moving it to a method
AAnton10/9/2022
did you turn that into a method? ok delay, sorry so your deserializer most likely favored the public constructor, even though there was a parameterless one just because it was private, the serializer decided to ignore it and now that there's no public constructors, it's forced to use the only available one
BBujju10/9/2022
Was the constructer called in a static context only cursed because it was reading a file, or is that still cursed
AAnton10/9/2022
I wouldn't make such things like config static at all. I'd load them in my main or wherever, and pass around explicitly or via dependency injection Reading a file in a constructor is definitely cursed
BBujju10/9/2022
My Main method switches to an async task which is where the config is used
AAnton10/9/2022
storing config in a static variable — somewhat cursed, but ok for one-off apps or if you're just learning the basics I'd load the config, then pass the config to the task why should the task touch globals at all? if you can make the dependency on that config explicit, do it explicit dependencies are a good thing. they are more verbose, but they make your program a lot more tractable in the long run
BBujju10/9/2022
So for every class that needs the config, I should make it into a non-static field and load it in the constructer?
AAnton10/9/2022
plus, if many tasks try to read that global at once, I think class initialization is under a lock, so they'd collectively sit and wait on the IO of loading the config from disk for no reason, blocking the worker threads, potentially wasting resources not load, pass it in as a parameter the loading shouldn't be done in the constructor in general, try to do the least work you can in the constructor the best constructor is one that just assigns fields
BBujju10/9/2022
Okay thanks !solved

Looking for more? Join the community!

Want results from more Discord servers?
Add your server
Recommended Posts
WPF reusing the same template across multiple columnsThe following question https://social.msdn.microsoft.com/Forums/silverlight/en-US/f84e0efd-b1f2-4ab6Cascading DropDownI'm using MVC (.NET5) with EF and had this code to select a species on a View (to Create/Edit): ```cAssembly service findingHi, I am trying to find out if it's possible to get IServiceProvider, Microsoft IConfiguration or sohow do i submit a progra min vs to google classroomim trying to submit a project that's due to today but when i do submit it all i get is this and not WPF custom property not recognized by the compilerI have defined a custom property like below, it's in the namespace `CarApp`. It is supposed to repreEntity Framework DbContextOptionsBuilder.UseSqlServer() missing definitionI just installed the newest version of Entity Framework (6.0.9) and am inside my program.cs trying tDoes API manual nuget downloads come with the package dependencies?-WPF passing binding to a template from DataGridTemplateColumnSay, I have a template like this in resources, which I want to reuse for multiple columns, and whichBest way to implement a regex based lexer [Answered]In a regex lexer, you can loop over every pattern and do something like this: ```cs if (match.Successtring query in C Sharpi am trying to get values from 2 website links and assign them to a lable using visual studio one is there a convention for validating login sessions with MVC?Assuming I'm using ASP, ADO and .NET Say I want to construct a project to have several functions thUsing SQL db to create object ID or application?I have an application where my records in my DB need to have unique IDs. Should I leave this responsObject Initializers - To Parenthesize or Not To Parenthesize (that is the question)What is the difference between the object initializers on lines 1 and 2? In what situations should oHow do I move my mouse curser on screen?I went through most of stack overflow and some YouTube tutorials but didn't fins anythingHow do I move my mouse curser on screen?i was wondering if its possible to move the curse on the screen using c#SQL Error when trying to get an IDI'm trying to add username password and email to my users table And then get the ID of this new userEF Structuring ProblemBasically I have users that I want to assign to a group. But I also want the group to have a parent,data transfer between classesI want to list 'uname' value in method X, to method Y i am new to oopA generic and efficient way to feed in text for a lexer or scannerIn the past I was lazy and always just shoved a string into my lexical analyzer as input, but what'sBlazor Re-render [SOLVED]Hello, I have a property stored in static class, and I would like to re-render some components that