Not sure what the System.NullRefrenceException is trying to tell me [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I am receiving this error and I'm not sure what it means?
Object reference not set to an instance of an object.

Variables in .NET are either reference types or value types. Value types are primitives such as integers and booleans or structures (and can be identified because they inherit from System.ValueType). Boolean variables, when declared, have a default value:
bool mybool;
//mybool == false
Reference types, when declared, do not have a default value:
class ExampleClass
{
}
ExampleClass exampleClass; //== null
If you try to access a member of a class instance using a null reference then you get a System.NullReferenceException. Which is the same as Object reference not set to an instance of an object.
The following code is a simple way of reproducing this:
static void Main(string[] args)
{
var exampleClass = new ExampleClass();
var returnedClass = exampleClass.ExampleMethod();
returnedClass.AnotherExampleMethod(); //NullReferenceException here.
}
class ExampleClass
{
public ReturnedClass ExampleMethod()
{
return null;
}
}
class ReturnedClass
{
public void AnotherExampleMethod()
{
}
}
This is a very common error and can occur because of all kinds of reasons. The root cause really depends on the specific scenario that you've encountered.
If you are using an API or invoking methods that may return null then it's important to handle this gracefully. The main method above can be modified in such a way that the NullReferenceException should never be seen by a user:
static void Main(string[] args)
{
var exampleClass = new ExampleClass();
var returnedClass = exampleClass.ExampleMethod();
if (returnedClass == null)
{
//throw a meaningful exception or give some useful feedback to the user!
return;
}
returnedClass.AnotherExampleMethod();
}
All of the above really just hints of .NET Type Fundamentals, for further information I'd recommend either picking up CLR via C# or reading this MSDN article by the same author - Jeffrey Richter. Also check out, much more complex, example of when you can encounter a NullReferenceException.
Some teams using Resharper make use of JetBrains attributes to annotate code to highlight where nulls are (not) expected.

In a nutshell it means.. You are trying to access an object without instantiating it.. You might need to use the "new" keyword to instantiate it first i.e create an instance of it.
For eg:
public class MyClass
{
public int Id {get; set;}
}
MyClass myClass;
myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...
You will have to use:
myClass = new MyClass();
myClass.Id = 0;
Hope I made it clear..

Another easy way to get this:
Person myPet = GetPersonFromDatabase();
// check for myPet == null... AND for myPet.PetType == null
if ( myPet.PetType == "cat" ) <--- fall down go boom!

Not to be blunt but it means exactly what it says. One of your object references is NULL. You'll see this when you try and access the property or method of a NULL'd object.

It means you did something like this.
Class myObject = GetObjectFromFunction();
And without doing
if(myObject!=null), you go ahead do myObject.Method();

If I have the class:
public class MyClass
{
public void MyMethod()
{
}
}
and I then do:
MyClass myClass = null;
myClass.MyMethod();
The second line throws this exception becuase I'm calling a method on a reference type object that is null (I.e. has not been instantiated by calling myClass = new MyClass())

Most of the time, when you try to assing value into object, and if the value is null, then this kind of exception occur.
Please check this link.
for the sake of self learning, you can put some check condition. like
if (myObj== null)
Console.Write("myObj is NULL");

what does this error mean? Object reference not set to an instance of an object.
exactly what it says, you are trying to use a null object as if it was a properly
referenced object.

Related

When is it correct to return a null reference type in C# [duplicate]

This question already has answers here:
Should a retrieval method return 'null' or throw an exception when it can't produce the return value? [closed]
(36 answers)
Closed 5 years ago.
I have a C# method that is expected to return an object. I would prefer if this method does not throw any exceptions.
My question is, is it acceptable to let the method return null and therefore give the null check responsibility to the caller without further warning?
Should the called assume that the object may be null, simply because it is a reference type? (And the default value of reference types are null:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null )
Please see my example below
// this method is expected to return an object
public MyClass getObject()
{
MyClass myObject = null;
// Another option would be to initialize to a new instance, calling the default constructor and not setting any properties
// MyClass myObject = new MyClass(); // no null check needed by the caller, but it is a pretty useless object
try
{
// just as an example
myObject = new MyClass();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return myObject; // will return null when and exception occured
}
public class MyClass
{
public int id { get; set; }
public string name { get; set; }
}
Yes you can return null likewise you are currently doing and in which case the responsibility lies to caller to check for nullity before trying to access any of the property of the object. Using C# 6 syntax
muobject?.Age
Per pattern you can use Null Object Pattern; in which case you return an empty object instead of returning null. Thus even if caller mistakes it won't blow up with a NullRefException. For validation purpose you can check for the property value like if(string.IsNullOrEmpty(myobject.name)) ....

C# HasValue in reference types

Is it somehow possible to use Nullable<>.HasValue on reference types?
Assume we have this example from value types:
int? a = GetNullOrValue(); // completely randomly gets random number or null
if (a.HasValue) return 0;
What I want to accomplish is this:
class Foo
{
public string Bar { get; set; }
}
Foo foo = GetNullOrFoo(); // completely randomly gets Foo ref. or null
if (foo.HasValue) return foo.Bar; // of course this will throw NullReferenceException if foo is null
I want to achieve this for better readability as I prefer "word stuff", not "symbol stuff" (x.HasValue instead of x != null).
You can write an extension method.
public static class Extension
{
public static bool HasValue<T>(this T self) where T : class
{
return self != null;
}
}
Then you can use
if (foo.HasValue()) return foo.Bar;
but, honestly x != null is simple, these kind of extension methods will be confusing for maintainers, I won't recommend it.
Also read further if you're going to use this approach. This will work only when there is no instance method named HasValue, if there is any instance method will be called, not the extension method. Hence it will result in NullReferenceException. Not to be surprised with the results. So think twice before you do this.
Always code as if the person who ends up maintaining your code is a
violent psychopath who knows where you live.
Quote from Code For The Maintainer

Invoking an Action - determine if the instance it belongs to is null

I have a method that takes an Action as a parameter. Actions are stored in a queue and executed when particular resources become available. Before I invoke an Action, I'd like to check if the instance it is a member of is null.
I did a simple test with the following stupid example. The Action invoked successfully after setting the invokee to null, and as expected, I got a NullReferenceException when attempting to access the property on the null invokee. Nothing jumped out at me when examining the Action at runtime that suggested I could determine if its instance was null.
I guess I could pass in the Action and the instance as parameters and test if the instance is null before invoking. Is it possible to test for a null invokee, or is this just a case of bad design on my part?
UPDATE:
I added the line,
if (explosion.Target != null)
to Bazooka.Fire(), to check for a null target, but it is still invoking the delegate in my example.
public void LetsDoThis()
{
var bazooka = new Bazooka();
var rocketLauncher = new RocketLauncher();
bazooka.LockAndLoad(rocketLauncher.BlowStuffUp);
rocketLauncher = null;
bazooka.Fire();
bool wasThisCompletelyAwesome = rocketLauncher.ThisIsAwesome;
}
public class RocketLauncher
{
public void BlowStuffUp()
{
bool stuffIsBlowingUp = true;
}
public bool ThisIsAwesome
{
get
{
return true;
}
}
}
public class Bazooka
{
private List<Action> explosions = new List<Action>();
public void LockAndLoad(Action loadIt)
{
this.explosions.Add(loadIt);
}
public void Fire()
{
foreach (Action explosion in explosions)
if (explosion.Target != null)
explosion.Invoke();
}
}
This won't work.
The Action does not in any way care about the original reference variable you got it from, it makes a copy of the reference value, and thus has its own reference.
Note that this also means that as long as you still have a reference to the delegate, even though you have no other references to the original object, it will still not be eligible for garbage collection.
The .Target property refers to the instance on which the method that the delegate refers to should be invoked, basically the this "parameter" to that method.
Thus, to have a null target you need to get the delegate from a static method, try this in LINQPad:
void Main()
{
Action a = Static.StaticMethod;
(a.Target == null).Dump();
}
public static class Static
{
public static void StaticMethod() { }
}
You can see that the delegate carries its own instance with this LINQPad code:
void Main()
{
Dummy d = new Dummy { Name = "A" };
Action a = d.Method;
d = new Dummy { Name = "B" };
Action b = d.Method;
d = null;
a();
b();
}
public class Dummy
{
public string Name { get; set; }
public void Method()
{
Debug.WriteLine("Name=" + Name);
}
}
The output here will be
Name=A
Name=B
As requested, let me clarify the difference between the instance, the reference, and the variable.
When you construct an object instance, like this:
var rocketLauncher = new RocketLauncher();
What you're doing is calling a method known as a constructor. The return value from this constructor is a reference to the newly constructed object. Basically, it's a pointer, meaning a memory address of where in the memory that object now lives. If it makes it easier to understand the rest of this answer you can consider it to be just a number.
Additionally you declared a variable, rocketLauncher, to hold this reference, this number.
Note that the object is separate from the variable, they're two distinct items. In one place in memory you have an object, in another place you have the variable containing the reference to that object, it's address, that number.
So when you do this:
bazooka.LockAndLoad(rocketLauncher.BlowStuffUp);
Let's simplify it a bit:
Action a = rocketLauncher.BlowStuffUp;
// bazooka.LockAndLoad(a);
let's forget about the part where we call that LockAndLoad method, and look at what happened when we "converted" the method BlowStuffUp into a delegate of type Action.
Basically, two things was "grabbed":
Which method to make the delegate refer to
The object instance on which to call that method
You can liken this to the following code:
MethodReference = rocketLauncher.BlowStuffUp;
object target = rocketLauncher;
// wrap this into a delegate
This now means you have two references to that object, one lives in the rocketLauncher variable, the other now lives inside the delegate.
What you do with that variable does not in any way change the value of that delegate, it still points to the same object as before. Basically it made a copy of that number. That number is still sitting there inside the delegate.
This is pretty much exactly the same as this:
int a = 10;
int b = a;
a = 0;
// b is still 10
So, to conclude, the .Target property of the delegate does not in any way know, or care, about the original variable that you got the delegate from. A copy was made of the reference value from that original variable, into the delegate, and what you do with the variable afterwards makes no difference at all.
So basically:
The instance is the object, it lives somewhere in memory
The reference is basically the address to it, and you can look at it as sort of a number
The variable is one place where you can store that reference
Now, what if you really want to make the delegate depend on the variable, and care about the value it now has, when you get around to calling it?
Well, one way would be to do this:
bazooka.LockAndLoad(delegate
{
if (rocketLauncher != null)
rocketLauncher.BlowStuffUp();
});
This would make an anonymous method, that would capture the variable itself, and then inside that anonymous method you could explicitly check what value the variable has at the time you call the delegate. If this part, about an anonymous method, does not make sense, you should ask another question here (ideally after reading a bit about anonymous methods, captured variables, and looked over some of the existing questions here on SO).
To test out an anonymous method, test the following code in LINQPad:
void Main()
{
object dummy = new object();
Action a = delegate
{
if (dummy != null)
Debug.WriteLine("not null");
else
Debug.WriteLine("null");
};
a();
dummy = null;
a();
}
It will print out:
not null
null
Use the Target property to check:
if(yourAction.Target != null) {
//...
}
Any Delegate type has a property called Target, so you can also use this for other types of delegate.
Update: In fact, when you use your Action to wrap some method of an object, that object won't never be disposed and that means the NullReferenceException can't be thrown in that case Unless you wrap another method of another object and this method has something to do with the null object.
Well, not in any way trying to argue with Lasse's rather detailed response, I would like to throw in my 5 cents on this.
When you invoke the LockAndLoad method of the bazooka class you simply add the method that's passed to the method to the List explosions collection of the bazooka class. Nulling the instantiation of the class whose method you had passed to the LockAndLoad method (in your example 'rocketLauncher') has NO effect on that collection, meaning that the Target property of the specific Action will not become null. You would have to explicitly remove the method from that collection BEFORE nulling the instantiation of the class.
bazooka.Unload(rocketLauncher.BlowStuffUp);
rocketLauncher = null;
Of course this works only if you modified your bazooka class to the following method in your bazooka class:
public void Unload(Action unloadIt)
{
if (explosions.Contains(unloadIt))
explosions.Remove(unloadIt);
}
This may not be what you are hoping for, but I hope it helped anyhow.

Can we interrupt creating an object in constructor

Could you help me please.
I have one idea but don't know how can I implement it.
So the question is:
Can we interrupt creating an object in constructor
i.e.
//Code
SomeClass someClass = new SomeClass(someCriteria);
So if someCriteria doesn't answer on our requirements we shouldn't create an object and should return null, instead of new object.
Is it possible to implement it in C#?
Best way is a factory class but if your class is so small you can use this:
class SomeClass
{
private string _someCriteria;
private SomeClass(string someCriteria)
{
_someCriteria = someCriteria;
}
public static SomeClass CreateInstance(string someCriteria)
{
if (someCriteria.Length > 2)
{
return new SomeClass(someCriteria);
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
// returns null
SomeClass someClass = SomeClass.CreateInstance("t");
// returns object
SomeClass someClass2 = SomeClass.CreateInstance("test");
}
}
You may want to use a factory class that creates instances of SomeClass returning null if the someCriteria is invalid.
It is quite usual that you check the constructor parameters if they are valid. If not, you usually throw an exception.
I also read a nice advice to provide static methods for validating constructor parameters. This enables the user of your class to check if whatever he is going to pass in the constructor will succeed or not. Those who are certain the parameters are ok (they made some sort of their validation) will go directly with the constructor.
Also consider what the user of your class will possibly do with null instead of the object (if some sort of factory class was used). Would this typically result in an NullPointerException on the next line? It's usually good idea to stop the wrong things as soon as possible, in this case throw the exception and finish. It is cleaner solution than returning null and if someone really wants to (this definetly won't be best practise) he can still catch this exception ...
If the parameters to your constructor are invalid, consider throwing ArgumentException or one of its descendant classes (e.g. ArgumentOutOfRangeException).
The new construct guarantees that an object will be returned (or an exception thrown). So as bleeeah recommended, a factory or similar concept will allow you to apply your logic.
That would be possible. Another way would be to put your checking in before you create the object. Like so
SomeClass someClass = null;
if (someCriteria == VALID)
{
someClass = new SomeClass(someCriteria);
}
Hope this helps.
No it is not possible directly.
You could throw an exception and add the required code to check for the exception and assign null to you variable.
A better solution would be to use a Factory that would return null if some condition fail.
var someClass = SomeClassFactory.Create(someCriteria);
if(someClass != null)
{
}

Why use the 'ref' keyword when passing an object?

If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?
For example:
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
The output is "Bar" which means that the object was passed as a reference.
Pass a ref if you want to change what the object is:
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);
void DoSomething(ref TestRef t)
{
t = new TestRef();
t.Something = "Not just a changed t, but a completely different TestRef object";
}
After calling DoSomething, t does not refer to the original new TestRef, but refers to a completely different object.
This may be useful too if you want to change the value of an immutable object, e.g. a string. You cannot change the value of a string once it has been created. But by using a ref, you could create a function that changes the string for another one that has a different value.
It is not a good idea to use ref unless it is needed. Using ref gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.
Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the ref keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. int), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:
int x = 1;
Change(ref x);
Debug.Assert(x == 5);
WillNotChange(x);
Debug.Assert(x == 5); // Note: x doesn't become 10
void Change(ref int x)
{
x = 5;
}
void WillNotChange(int x)
{
x = 10;
}
You need to distinguish between "passing a reference by value", and "passing a parameter/argument by reference".
I've written a reasonably long article on the subject to avoid having to write carefully each time this comes up on newsgroups
In .NET when you pass any parameter to a method, a copy is created. In value types means that any modification you make to the value is at the method scope, and is lost when you exit the method.
When passing a Reference Type, a copy is also made, but it is a copy of a reference, i.e. now you have TWO references in memory to the same object. So, if you use the reference to modify the object, it gets modified. But if you modify the reference itself - we must remember it is a copy - then any changes are also lost upon exiting the method.
As people have said before, an assignment is a modification of the reference, thus is lost:
public void Method1(object obj) {
obj = new Object();
}
public void Method2(object obj) {
obj = _privateObject;
}
The methods above does not modifies the original object.
A little modification of your example
using System;
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t = new TestRef();
t.Something = "Bar";
}
}
public class TestRef
{
private string s;
public string Something
{
get {return s;}
set { s = value; }
}
}
Since TestRef is a class (which are reference objects), you can change the contents inside t without passing it as a ref. However, if you pass t as a ref, TestRef can change what the original t refers to. i.e. make it point to a different object.
With ref you can write:
static public void DoSomething(ref TestRef t)
{
t = new TestRef();
}
And t will be changed after the method has completed.
Think of variables (e.g. foo) of reference types (e.g. List<T>) as holding object identifiers of the form "Object #24601". Suppose the statement foo = new List<int> {1,5,7,9}; causes foo to hold "Object #24601" (a list with four items). Then calling foo.Length will ask Object #24601 for its length, and it will respond 4, so foo.Length will equal 4.
If foo is passed to a method without using ref, that method might make changes to Object #24601. As a consequence of such changes, foo.Length might no longer equal 4. The method itself, however, will be unable to change foo, which will continue to hold "Object #24601".
Passing foo as a ref parameter will allow the called method to make changes not just to Object #24601, but also to foo itself. The method might create a new Object #8675309 and store a reference to that in foo. If it does so, foo would no longer hold "Object #24601", but instead "Object #8675309".
In practice, reference-type variables don't hold strings of the form "Object #8675309"; they don't even hold anything that can be meaningfully converted into a number. Even though each reference-type variable will hold some bit pattern, there is no fixed relationship between the bit patterns stored in such variables and the objects they identify. There is no way code could extract information from an object or a reference to it, and later determine whether another reference identified the same object, unless the code either held or knew of a reference that identified the original object.
This is like passing a pointer to a pointer in C. In .NET this will allow you to change what the original T refers to, personally though I think if you are doing that in .NET you have probably got a design issue!
By using the ref keyword with reference types you are effectively passing a reference to the reference. In many ways it's the same as using the out keyword but with the minor difference that there's no guarantee that the method will actually assign anything to the ref'ed parameter.
ref mimics (or behaves) as a global area just for two scopes:
Caller
Callee.
If you're passing a value, however, things are different. You can force a value to be passed by reference. This allows you to pass an integer to a method, for example, and have the method modify the integer on your behalf.

Categories