-5

I have the following code:

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            var obj=(person)Activator.CreateInstance(typeof(person));
            Console.WriteLine(obj);
        }
    }
     public class person
        {
            public int id { get; set; }
            public string name { get; set; }
            public DateTime dob { get; set; }

            public override string ToString()
            {
                return id.ToString() + " " + name + " " + dob.ToString();
            }
        }
}

which yields the following output:

0  1/1/0001 12:00:00 AM

However, if change the person.ToString() to the following:

public override string ToString()
{
        return id.ToString() + " " + name.ToString() + " " + dob.ToString();
}

I get the following error:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Rextester.person.ToString()

Can someone shed some light on it.

Edited

Babu James
  • 2,431
  • 4
  • 29
  • 48
  • 7
    1) So...how is that line different than your code above? 2) Why are you using `Activator` and not just the constructor? – Servy Aug 23 '13 at 14:55
  • possible duplicate of [What is a NullReferenceException in .NET and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net-and-how-do-i-fix-it) – User Aug 23 '13 at 14:55
  • 1
    Why not just use the default constructor for `person`? Also I can't tell what you changed. – BrianM Aug 23 '13 at 14:58
  • @SamLeach No, it's not. The stack trace alone proves that. – Servy Aug 23 '13 at 15:03
  • 4
    Please edit your answer to tell use what change you really made to Person.ToString. Without that, it's hard to answer your question. – hatchet - done with SOverflow Aug 23 '13 at 15:07

1 Answers1

4

I'm guessing your code samples aren't correct as it stands in your question and you're actually seeing this behavior:

return id.ToString() + " " + name + " " + dob.ToString(); 

works

return id.ToString() + " " + name.ToString() + " " + dob.ToString();

doesn't work

This is because adding a null value to a string is legal but calling a method on a null instance is not.

See this question: Why is adding null to a string legal?

Community
  • 1
  • 1
nvuono
  • 3,193
  • 23
  • 26
  • 2
    @Servy - it's not the code he's posted, but clearly the code he's posted is not right since it's identical to the first version. nvuono's guess at what was intended makes a lot of sense. – hatchet - done with SOverflow Aug 23 '13 at 15:14
  • 2
    @hatchet There are any number of things that could be done instead as well. Rather than guessing, it's more productive to simply wait for the OP to edit his *real* code in. – Servy Aug 23 '13 at 15:17