-2

I have wrote the code snippet on dotnetfiddle.net with compiler settings set to .NET 7

using System;

public class Person
    {
        private string fname;
        private string lname;
        private int ide = 30;
        public Person(string fN, string lN)
        {
            fname = fN;
            lname = lN;
        }
        public bool ID() => GetType().GetProperty("ide").GetValue(this, null).Equals(30);
    }

public class Program
{
    public static void Main()
    {
        Person p = new Person("Mandy", "Dejesus");
        p.ID();
    }
}

I have checked others questions who have received the same warning and they seem to suggest creating an object with the new keyword. I've done that yet I still get the error. What am I doing wrong?

I expect true but I'm currently getting

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object 
   at Person.ID()
   at Program.Main() 
gunr2171
  • 16,104
  • 25
  • 61
  • 88
jfar41
  • 59
  • 8
  • 2
    Why are you using reflection to get the current instance's field value rather than directly reading it? – gunr2171 Dec 29 '22 at 22:30
  • 4
    In addition, `ide` is not a property (so no "GetProperty"), it's a field. – gunr2171 Dec 29 '22 at 22:33
  • For context, I'm working on a legacy codebase. They have some code written in the same fashion and I just extracted that format to see why they took that approach. I'm fairly new to C#. Not sure why they took that approach. I'm still learning but from your standpoint can you imagine a case in where using reflection is better than directly reading it? – jfar41 Dec 29 '22 at 22:35
  • 2
    You'd use reflection if you don't know the name of the field/property at compile time. And even if that's the case, there are other data types you can use that are far faster (such as Dictionaries). Reflection is _slow_. – gunr2171 Dec 29 '22 at 22:36
  • This is helpful. Thanks for the insight. It's tricky coming into a new codebase and understanding why they took what seems to be a longwinded approach – jfar41 Dec 29 '22 at 22:38
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Klaus Gütter Dec 30 '22 at 07:40
  • @KlausGütter Not exactly. It explains what is null and where it may arise but for a novice, understanding how to use this for a particular use case is tricky. Francesc gave a great break down of the logic in my code which helped me tremendously for my use case a well as gunr2171 comment on why the last programmers used reflection – jfar41 Jan 03 '23 at 16:29

3 Answers3

3

You are getting a NullReferenceException because you are executing GetValue on a null. The reason is as follows:

In this line:

GetType().GetProperty("ide").GetValue(this, null).Equals(30);

The first part GetType() returns the Type of your Person class. Then you execute GetProperty("ide") on it, but ide is not a property, it's a field. Therefore GetProperty() returns null and executing GetValue throws the NullReferenceException.

One potential solution is to make ide an actual property instead of a field:

private int ide {get; set;}

Note: You might want to call it Ide instead, but then rename it in the GetProperty parameter.

This should fix your issue, but as others have said in the comments, you might want to refactor the code to achieve the same result in a much cleaner way.

Francesc Castells
  • 2,692
  • 21
  • 25
2

Your ID function makes no sense and seems to call a bunch of functions that don't exist or aren't necessary.

Here is the correct function.

public bool ID() {
     return this.ide == 30;
}
MrDiamond
  • 958
  • 3
  • 17
2

Let's assume you wanted to keep using Reflection. What would you actually need to do?

Francesc Castells has the right explanation for where the NRE comes from. To fix the code essentually you'd need to change out GetProperty() for GetField().

However, that's not good enough, because ide is a private field. So you need to tell Reflection to include searching for private fields as well.

using System.Reflection;

// ...

public bool ID() => GetType().GetField("ide", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this).Equals(30);

Still not very pretty. Go with the right way.

gunr2171
  • 16,104
  • 25
  • 61
  • 88