Why would a NullReferenceException get thrown because my method returns null? [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
As shown below I have a method in my class that returns null as expected when it does not successfully read a value. I assume that the object "test" would just be set to NULL but for some reason an error is getting thrown.
I don't understand why this would throw an error...
private string myNullFunction() { return null; }
private void myFunction()
{
object test = myNullFunction();
}
when this does not...
private void myFunction()
{
object test = null;
}

Your sample code does not actually throw an exception. The real issue is shown in the code snippet above the exception dialog: m_xml.Read is returning null, but you are trying to access the Value property.

Read function is returning null. That's why null reference exception is there.

Related

boolean on the script, is saying error that says "not all code path return a value" for the function C# Unity [duplicate]

This question already has answers here:
C# compiler error: "not all code paths return a value"
(9 answers)
Closed 21 hours ago.
I am getting an error message That "not all code paths return a value" for this code.
public bool IsInteractable(Vector3Int position)
{
//getting the tile
TileBase tile = InteractableGround.GetTile(position);
//Checking the name of the tilemap
if (tile != null)
{
if (tile.name == "Interactable")
{
return true;
}
return false;
}
}
I think the issue might be with the string for the file name, but i have copy and paste the name of the tile.
It’s because when your if statement condition is not met your if block is skipped right? So the code inside your if statement is not executed.
You need to include a return false or similar after your if statement or in an else statement :)
This error means that there is one possibility where your code won't have a return statement.
Here, if your tile is null, you don't return anything, which is causing C# to throw this error.

What is the best way to return from a function that use using block? [duplicate]

This question already has answers here:
What happens if i return before the end of using statement? Will the dispose be called?
(5 answers)
Closed 7 months ago.
What is the best way between those two implementations of using statement:
I wonder if the 2nd code prevent using from releasing the resource/ calling ondispose because of the return command?
1st code:
public byte[] DeriveSharedKey()
{
byte[] returnValue = null;
using (some resources)
{
some inner workings with resource...
returnValue = some_values;
}
return returnValue;
}
2nd code:
public byte[] DeriveSharedKey()
{
using (some resources)
{
some inner workings with resource...
return some_value;
}
}
The using statement will automatically call the Dispose method on the object once the program leaves the scope it's in, either way will work, the bottom one is just more compact.

C# Task.Result is Null [duplicate]

This question already has answers here:
'await' works, but calling task.Result hangs/deadlocks
(6 answers)
Closed 4 years ago.
I have following method which will eventually return some Task<IList<DataModel>> but for now just returns null. I want to load result of this list to ObservableCollection in my ViewModel which is then displayed in a ListView.
But for now, I just want to return null and check that that is handled properly, so my ListView should show nothing in it as a result. I simmulate that by this code:
public async Task<IList<DatatModel>> GetData(string id)
{
return await Task.FromResult<IList<DataModel>>(null);
}
I call the code above and will loop through result of my Task and load it all in my ObservableCollection like so:
public void Initialize()
{
foreach (var data in GetData(Id).Result)
{
MyObservableCollection.Add(data);
}
}
However, my app just freezes. I think that above call to GetData(id).Result is problem because Result is null. How do I loop through this data and load it into my ObservableCollection if some data exist, or simply dont load anything if there is no data returned?
Instead of returning null, return an empty List<DataModel>. That way, your Result property will always be populated. So, your GetData method would become:
public async Task<IList<DatatModel>> GetData(string id)
{
return await Task.FromResult<IList<DataModel>>(new List<DataModel>());
}

Getting The Method That A Method Was Called From? [duplicate]

This question already has answers here:
How can I find the method that called the current method?
(17 answers)
Closed 6 years ago.
Is it possible to determine the calling method name "Eat Pizza" in PostError?
I guess I could pass "EatPizza" as one of the arguments, but that would require changes each time the method name changes (unnecessary maintenance). But then, I wasn't even able to find the method name "EatPizza" in the context of "EatPizza" (using stacktrace, getframe, getmethod).
public void EatPizza(Pizza p){
if(p==null){ //A arbitrary made up error
Utilities.PostError();
}
else{
p.Slices -= 1;
}
}
...
public void PostError(){
//Basically posting to database the name of the method
//Tried this, didn't work: (new StackTrace(true)).GetFrame(5).GetMethod().Name
//Is it possible to determine the calling method name "Eat Pizza" in this context?
}
When I try different values (0 to StackTrace.FrameCount-1) in StackTrace.GetFrame, I get the following values, when I just want "EatPizza":
.ctor
ThreadStart
Main
_nExecuteAssembly
RunUsersAssemblyDebugInZone
You were on the right track with creating a StackTrace object, but you seem to have misunderstood the argument to GetFrame. Frames are numbered from the bottom-most frame, so:
GetFrame(0) would return PostError
GetFrame(1) would return the caller of PostError
So just try this:
var trace = new StackTrace(true);
WriteToDB(trace.GetFrame(1).GetMethod().Name);
Personally, I would prefer to get the entire stack trace rather than just the caller, so I'd do this:
var trace = new StackTrace(true);
WriteToDB(trace.ToString());
Is it possible to determine the calling method name "Eat Pizza" in PostError? I guess I could pass "EatPizza" as one of the arguments, but that would require changes each time the method name changes (unnecessary maintenance).
Calling PostError in all the methods in which something could go wrong is also "unnecessary maintenance". It also complicates the execution flow of your program, because you will have to check for errors all over the place, and high-level processes will have to check if the low level processes completed successfully.
It is better to use the exception handling structures provided by the CLR and C#.
The exact location in which the error occured is stored in the exception's StackTrace property.
pubic void BigDinnerEatingProcess()
{
try
{
WhateverHappensAtTheTopLevel();
}
catch (PizzaNotDeliveredException ex)
{
Utilities.PostError(ex);
MessageBox.Show("Dinner was not eaten. Please make sure the pizza is delivered.");
}
}
public void EatPizza(Pizza p)
{
if (p == null)
throw new PizzaNotDeliveredException();
p.RemoveOneSlice();
}
private void PostError(Exception ex)
{
string errorLocation = ex.StackTrace;
//...
}

Why can I write a generic catch statement in C# that does nothing? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why can’t I catch a generic exception in C#?
I have been reviewing and writing Circuit Breaker code recently. The following method compiles, but the catch block is never entered. I have plenty of work-arounds, and this isn't the only way to get the right behavior (filtering exceptions), but I'm curious why this compiles and doesn't work!
public void AttemptCall<TException>(Action action)
where TException : Exception
{
try
{
action();
}
catch(TException e) // This block is never entered!
{
state.ActUponException(e);
throw;
}
}
Here is a test that should enter the catch block of the previous method.
[TestMethod]
public void Throw_an_exception()
{
circuitBreaker.AttemptCall<Exception>(() => throw new Exception());
// test the circuit breaker's state
}
Its a bug https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0

Categories

Resources