Resolved Why am I getting NullReferenceException trying to display Assembly Version?

chairmanPC

Active member
Joined
Apr 19, 2021
Messages
38
Programming Experience
10+
It's a .NET framework project. And I get the NullReferenceException when I try to print the project version.

C#:
        public Form1()
        {
            label3.Text = Assembly.GetExecutingAssembly().GetName().Version.ToString(); <-- offending line
            InitializeComponent();
        }

What did I do wrong?
 
Solution
You need to put your own initialisation code after the call to InitializeComponent. That's the method that executes the code generated by the WinForms designer, to create and configure the controls on the form. If your controls, including that Label, have not been created yet, how could you set the Text property?

You should have at least been able to narrow it down to that reference for yourself, even if you didn't know what to do about it. VS has a debugger for a reason so you need to use it. You should have looked at every reference on that line to see which one was null. You may even have been able to work the problem out for yourself once you had that information but, if not, at least you could tell us what...
You need to put your own initialisation code after the call to InitializeComponent. That's the method that executes the code generated by the WinForms designer, to create and configure the controls on the form. If your controls, including that Label, have not been created yet, how could you set the Text property?

You should have at least been able to narrow it down to that reference for yourself, even if you didn't know what to do about it. VS has a debugger for a reason so you need to use it. You should have looked at every reference on that line to see which one was null. You may even have been able to work the problem out for yourself once you had that information but, if not, at least you could tell us what actually happens when you run the code, instead of us having to guess or work it out for ourselves. ALWAYS debug your code thoroughly before posting a question and provide ALL the relevant information. If you don't know how to debug, you should stop what you're doing and learn now, because it is an essential skill for all developers that is sadly overlooked by most programming classes/courses.
 
Solution
Back
Top Bottom