C# - internal static readonly is null on access [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have the following code:
internal class FakeInvitationsRepository : InvitationsRepository
{
internal readonly static Dictionary<Guid, InvitationDbEntity> Data = new Dictionary<Guid, InvitationDbEntity>()
{
{ ...
Here's a screen-shot, for what its worth:
It's just some in-memory fake data, 3 items in all. The class lives inside an ASP.NET WebAPI project, not in a test DLL but in the WebAPI DLL for the time being.
An API call comes in and hits a breakpoint in the controller action where it tries to consume this fake data directly, no IoC yet or anything clever.
But the field Data is null. It's causing a null ref exception at runtime.
The C# language spec says:
If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.
What's happening here such that the field is not initialized prior to first-use?
Note: A colleague has quickly sanity checked and is also bemused. Data is only ever set, never nulled by my code (its readonly afterall).
Edit
Here's the callstack of just my code:
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
{ at Company.Product.WebAPI.Controllers.RenamedController.<GetInvitations>d__14.MoveNext()
at Company.Product.WebAPI.Controllers.RenamedController.GetInvitations(Guid id)
at lambda_method(Closure , Object , Object[] )
at Company.WebAPI.Product.Areas.RouteDebugger.InspectActionInvoker.InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
at Company.WebAPI.Product.Areas.RouteDebugger.InspectHandler.<>n__FabricatedMethod12(HttpRequestMessage , CancellationToken )
at Company.WebAPI.Product.Areas.RouteDebugger.InspectHandler.<SendAsync>d__e.MoveNext()
at Company.WebAPI.Product.Areas.RouteDebugger.InspectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
}
FrameCount: 84
frames: {System.Diagnostics.StackFrame[87]}
m_iMethodsToSkip: 3
m_iNumOfFrames: 84
Answer
I can't answer because the question was put on hold. Debatable.
Thanks to MStodd. The answer is silly and straight-forward, but somewhat surprising; I don't recall having ever seen this in 11 years of .NET programming.
The Data field was not yet initialized.
Placing a breakpoint in the initializer, the entire block goes red, showed that it was called on the next step.
The NullReferenceException was a red-herring and due to this.Invitations being null.
Of course, I was expecting the field to be initialized by the time that line is stopped at, I just didn't expect it to happen so late, and so assumed the null was causing my runtime exception.
There you go.

From your call stack i can deduce that the Invitations property is evaluated(in the Select body). Being the last one on the call stack i can deduce that the null reference raises due to the fact that Invitations is NULL!). I suppose that Data = NULL is NOT related to the call stack at all! but rather it is a debugger issue.

Related

C# action invoke is changing `this` [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 18 hours ago.
Improve this question
TL;DR
If a C# Action referencing a class method still has a reference to the original Target, then why is this being changed when I invoke the Action and set breakpoints in that method?
More Context
I have the following setup in a .NET project:
// MyClass.cs
public class MyClass
{
private float _someValue = -1f;
private int _instanceId = 12345;
public void Method()
{
Updater.Instance.RegisterUpdate(_instanceId, doStuff);
}
private void doStuff(float deltaTime)
{
// Do stuff with _someValue
}
}
// Updater.cs
public class Updater
{
public static Updater Instance = new();
private readonly List<Action<float>> _updateActions = new();
public void RegisterUpdate(int instanceId, Action<float> updateAction)
{
// Validation...
_updateActions.Add(updateAction);
}
public void Update()
{
foreach (Action<float> action in _updateActions)
action.Invoke(Time.deltaTime);
}
}
Essentially, Updater wraps a list of registered Actions, and invokes them all when Update is called.
In Visual Studio, I can set breakpoints in MyClass.doStuff(), and they are getting hit when Updater.Update() is called. Unfortunately, while paused on a breakpoint, I get no value when I hover over the value of _someValue, nor is the field even mentioned in the Locals Window, and when I enter _someValue in the Immediate Window, I get "The identifier _someValue is not in the scope". In addition, the this value in the Locals Window is of type Updater, not MyClass.
And yet, everything is working fine. The conditional logic inside doStuff that works with _someValue is still working as expected when I step through, I just can't inspect the values as I step, which makes things difficult to debug. Also, when I go up the call stack to Updater.Update and inspect the current element of _updateActions, I can see that its Target property is correctly set to the instance of MyClass. So what is happening here? Trying to figure out what this is feels like JavaScript crap lol, not C#.
Turns out the issue was something in my actual code that was not captured in the minimum working example in my question. That is, in my real code, doStuff was a local function inside of Method. If doStuff is a separate method, as in my question, then this is of the correct MyClass type. Strangely, I can only repro the this-changing behavior of local functions in Unity components, not in vanilla C# classes, so this may be a result of the Mono compiler that Unity uses on the backend.
Anyway, thank you to the commenters for helping me get here. Hopefully this helps someone in the future.

Index out of bounds, but index is actually within bounds C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
My C# (unity) application claims that an index I am trying to access within an array of strings is out of the bounds of the array. It is not. Here is the array:
public string[] fen =
{
"2q3k1/8/8/5N2/6P1/7K/8/8 w",
"7k/8/8/4b1n1/8/8/5PPP/5R1K w",
"r1bqkb1r/pppp1ppp/2n5/4p3/2B1N3/5N2/PPPP1PPP/R1BQK2R b"
Here is the code accessing it:
void Update()
{
if (PuzzleVariables.instance.puzzlePassed)
{
if (PuzzleVariables.instance.fen.Length < PuzzleVariables.instance.puzzlenumber + 1)
{
SceneManager.LoadScene("ModuleCompleted");
}
else
{
PuzzleVariables.instance.puzzlePassed = false;
FENbuild(PuzzleVariables.instance.fen[PuzzleVariables.instance.puzzlenumber -1]);
}
}
}
Instead of moving on to the next puzzle, it goes on to the ModulePassed screen.
Whenever I try printing the length of this array, it reads 1. What am I doing wrong here?
First
When the runtime says that you are out of bounds, then you ARE out of bounds.
There is no point in arguing that you are not out of bounds with the runtime. Empirically, almost everytime people discuss with their compiler, (ignoring the fact that the compiler is a bad discussion partner because it will not talk back to you but stubbornly repeat his argument over and over, and is not convincable, and immune to threats of all sorts, like throwing pc out of the window and such), it turns out: compiler is right, you are wrong. So skip that episode, and search for the mistake you made instead.
Second
If Puzzlenumber is anything other than 1, 2, or 3, or the Array is shorter than that (non initialized, using wrong array, etc), this will crash. Place a breakpoint on the line where you access your array, and check your variable and also check PuzzleVariables.instance.fen.Length. You might have initialized something you dont use.
Third
Stacktrace. Check your stacktrace to see if your line crashes, or the crash is WITHIN the method FENbuild. Maybe your input is working, but causes a crash down there.
Fourth
Singletons are only used when there is a technical reason for a class to have only one instance, (i.e. resource, printer, etc.).
Is there a reason why you do not work with normal instances? If not, singleton is an Antipattern.
Is say this, because singletons, can have side effects that also make your thing crash. Especially in a multithreaded environment like unity is.
Fifth
In Unity Inspector a public string[] fen; might be serialized => it can have totally different content assigned in the inspector, be empty etc. Changing the code afterwards doesn't change the already serialized array => The Inspector overrules any later changes in code unless you Reset the component
In short:
Please post stacktrace and maybe some reproducable code, and never use singletons.

Visual Studio said my variables are useless in a private method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have simple scenario where I started to repeat same code multiple times, so I decided to move it in a private method, depending on a if/else it's being edited and my variables that are listed below might overwrite it's value which is perfectly fine:
ProductResponse identificationResults = new ProductResponse(); // I understand this assignment gets overridden in private method below but that is goal
long? productIdentificationRecordId = null; // I understand this assignment gets overridden in private method below but that is goal
I'm invoking my method on a few places in a code that's reason why I created private method to avoid code repetition in same file:
await SetProductStatusAndPerformDbActions(productCompany, userId );
private async Task SetProductStatusAndPerformDbActions(Company productCompany, long userId, ProductType productType, ProductStatus status, long? productIdentificationRecordId, ProductResponse identificationResults, CancellationToken cancellationToken)
{
status = GetCompanyProductStatus(productCompany.Id, identificationResults);
productIdentificationRecordId = await PerformDbAction(status, productType, userId, cancellationToken); // underlined this code
identificationResults = await IdentifyCompanyProduct(productCompany, cancellationToken); // underlined this code
}
Visual Studio says 'Remove this useless assignment to a local variable
productIdentificationRecordId'
Visual Studio says 'Remove this useless assignment to a local variable
identificationResults'
I understand this assignments gets overridden in private method below but that is point of private method because I want to use for example productIdentificationRecordId and its new value right after I call this private method because goal of private method is to modify it and that is it..
I'm not using vars which might cause this warning so I don't know what to do here.
How this could be written to avoid this scenarios ?
Edit:
Added screenshot from the private method, variables are grayed as they are not used:
Because these parameters are not being passed by reference, setting them to any value will only change the value of the parameter variables local to your helper method: it will not impact the values that were passed in to those parameters.
Since you don't use the new values you're assigning to those parameters inside the method, Visual Studio is smart enough to recognize that setting values to them has no effect. It's warning you about that, which is good because in this case you might think your code is doing something that it's not really doing.

How reuse a instance of a object for all functions requests? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am working on a azure function that makes dependency injection of a object, and I would like to know what I can do to it's create the instance just once in the constructor (when I deploy the function to production) and at the others requests to the functions reuse the first instance created.
I made a injection dependency of the object that I want to reuse but it don't worked.
There is no "function scope" variable in C# like there is in Native C++. But there is a bunch of similar constructs you can use:
Make a property with Public get but private Set. That way only class code (like the constructor) can set values. You see this pattern used abundantly all over the .NET Framework. However it does not really avoid setting the value in class code by accident. It works best if you never use this value anywhere else in classcode.
Another option is the "readonly" variable attribute. It enforces that the value must be set once (in the Constructor), but can also only be set once. You would still have to hand in the instance to the constructor or use static.
Another option is to add a static variable to store the data. But that is a pattern that is absolutely not adviseable. If you never need a second set of these instances with a different shared value, you have lost. And this will happen, as sure as the Garbage Collection. We got literal decades worth of experience of static values backfiring. So you really should stay with instance variables.
Another way is to add a Factory method. Often they are used if the instances need setup you can not leave to the average programmer using your code. You could even slightly breakt the pattern by having both a public constructor and a instance Factory Method. If you use the factory method, the shared thing is copied over from them Instance it is called on. If you use the Public constructor, a new shared thing is created.
The way to reuse a resource among multiple instances of the function is to declare it as static. For example, let's say I want to reuse an HttpClient:
public static class PeriodicHealthCheckFunction
{
private static HttpClient _httpClient = new HttpClient();
[FunctionName("PeriodicHealthCheckFunction")]
public static async Task Run(
[TimerTrigger("0 */5 * * * *")]TimerInfo healthCheckTimer,
ILogger log)
{
string status = await _httpClient.GetStringAsync("https://localhost:5001/healthcheck");
log.LogInformation($"Health check performed at: {DateTime.UtcNow} | Status: {status}");
}
}

Is changing the reference of a list and reading from it at the same time threadsafe? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've implemented this model to avoid locks where I'm trying to fully replace the contents of a list, while reading from it.
Reference assignment is an atomic operation, but I don't really understand what happens if a read/iteration on the list is in progress while the reference is changed. Is this implementation correct?
public class Cache
{
IList<CacheEntry> cache = new List<CacheEntry>();
// this method gets called frequently
public CacheEntry GetForCompany(string companyId)
{
return this.cache.Where(c => c.id == companyId).FirstOrDefault();
}
// this method gets called every 5 minutes
public void OnUpdate(IEnumerable<CacheEntry> updatedCache)
{
this.cache = updatedCache.ToList();
}
}
Are the any issues or race conditions with the code above?
Its thread safe in the sense than nothing will actually break or fail but, Linq being lazy, if the Where clause is materialized a considerable time later than the call to GetForCompany you can get very stale results because the query will return the results of the dated cache, even if the cache has been updated in the mean time.
Are the any issues or race conditions with the code above?
It might result in something similar to phantom read. So the answer will be PhantomRead.BelongsTo(RaceCondition)
I will explain it in low level pointer way even though you can't access it in c#
after the call OnUpdate this.cache pointer will be pointing to a memory address lets say 0x4
Then you called GetForCompany. The .Where call will store the current address of this.cache which is 0x4
Then you called OnUpdate again and this.cache became 0x100
When the Where clause enumerate thru the list it will still be looking at the list located at 0x4. Which means there are actually two sets of list in the memory at that time. The one stored in linq is 0x4 and the new one is 0x100.
Enumerating thru 0x4 will not give you any trouble since that list is not modified at all

Categories