C
C#3w ago
Faker

✅ 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:
C#
class MyClass
{
private int[] numbers;
private string someVariable;

public MyClass() // default constructor
{
someVariable = "";
}
C#
class MyClass
{
private int[] numbers;
private string someVariable;

public MyClass() // default constructor
{
someVariable = "";
}
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
Angius
Angius3w ago
$tias
Faker
FakerOP3w ago
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
No description
Faker
FakerOP3w ago
yep I obtain this so internally, numbers is pointing to Null but why?
Angius
Angius3w ago
Because you didn't tell it to point to anything else
kocha
kocha3w ago
the default value of all reference types is null
Angius
Angius3w ago
So what is it supposed to point to? In general, default values for any type is default(T)
Faker
FakerOP3w ago
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?
jcotton42
jcotton423w ago
Z, you just said “the default value is the default value” :kek:
kocha
kocha3w ago
you first need to create an array, them you can assign that instance to the field.
Angius
Angius3w ago
Eh, kinda lol "default value" is kinda abstract, default(T) returns a concrete value
Faker
FakerOP3w ago
can 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?
Angius
Angius3w ago
Basically, yeah
Faker
FakerOP3w ago
yep, thanks !
Mąż Zuzanny Harmider Szczęście
basically you reserve a memory address but dont asing anything to it $close
MODiX
MODiX3w ago
If you have no further questions, please use /close to mark the forum thread as answered

Did you find this page helpful?