✅ NullReferenceException when declaring an array but not initializing it
Hello guys, say I created a new class and within that new class, I created an array.
So we have something like this:
Noticed that we didn't initialize numbers array. So what will happen if we try to access it? we get a NullReferenceException? If so, what is happening internally pls. Like when we declare
int[] numbers
, normally numbers should store a reference to where the array is on the heap, right? But since their is no "array" yet, numbers points to nothing, so to null?17 Replies
$tias
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at Learning.MyClass.Main(String[] args) in C:\Users\ridgh\RiderProjects\Learning\Learning\MyClass.cs:line 16

yep I obtain this
so internally, numbers is pointing to Null but why?
Because you didn't tell it to point to anything else
the default value of all reference types is null
So what is it supposed to point to?
In general, default values for any type is
default(T)
yeah I see
by default when I create the array but don't initialize it, the array points to null unless I assign it some values where it will points to the new values?
Z, you just said “the default value is the default value” :kek:
you first need to create an array, them you can assign that instance to the field.
Eh, kinda lol
"default value" is kinda abstract,
default(T)
returns a concrete valuecan we think of declaring reference type without initializing them as follows pls:
when we declare but don't initialize a reference type, what happens is that, we only allocate memory when we store data, since no data is stored yet, we don't waste memory, so reference type points to null?
Basically, yeah
yep, thanks !
basically you reserve a memory address but dont asing anything to it
$close
If you have no further questions, please use /close to mark the forum thread as answered