I’ve recently started trying to teach myself C# and this is very much a beginner’s attempt at the implementation of using business rules in a property, in my case the FurColor. When I run the program below I get a NullReferenceException. Can someone help me find the cause of this error? The exception occurs at line 15
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _10_23_Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("programming practice!");
Dog d = new Dog();
Console.Write("what color is your dog: ");
d.FurColor = Console.ReadLine();
Console.WriteLine("the color of your dog is {0}", d.FurColor);
}
}
class Dog
{
private string furColor;
private string petName;
private int tagNum;
public Dog() { }
public Dog(string color, string name, int tagID)
{
furColor = color;
petName = name;
tagNum = tagID;
}
//properties
public string FurColor
{
get { return furColor; }
set {
do
{
Console.Write("enter in a viable color type: ");
}
while (furColor.Length > 10);
furColor = value;
}
}
public string Name
{
get { return petName; }
set { petName = value; }
}
public int TagNum
{
get { return tagNum; }
set { tagNum = value; }
}
}
}
Once corrected you will get an infinite loop though.
Side note : You should not ask for input in the Set clause of your property.
You should prefer a member function that would ask for the input, check if it’s valid and then set the color.
In you dog class add a function that looks like this :