Patrick
Patrick

Reputation: 884

Interface Property Usage

I get an error when run the console app since obviously instance of P doesnt exist. What I cant understand is where should be "newing" it? Should it be in the constructor of Employee (that didnt work when I tried) ??

public class Person
{
    private string name;
    public string Name  // read-write instance property
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }
}

interface IEmployee
{
    Person P
    {
        get;
        set;
    }

    int Counter
    {
        get;
    }
}

public class Employee : IEmployee
{
    private Person p;
    public static int numberOfEmployees;
    public Person P  // read-write instance property
    {
        get
        {
            return p;
        }
        set
        {
            p = value;
        }
    }

    private int counter;
    public int Counter  // read-only instance property
    {
        get
        {
            return counter;
        }
    }

    public Employee()  // constructor
    {
        counter = ++counter + numberOfEmployees;
    }
}
class Program
{
    static void Main(string[] args)
    {
        System.Console.Write("Enter number of employees: ");
        Employee.numberOfEmployees = int.Parse(System.Console.ReadLine());

        Employee e1 = new Employee();
        System.Console.Write("Enter the name of the new employee: ");
        e1.P.Name = System.Console.ReadLine();

        System.Console.WriteLine("The employee information:");
        System.Console.WriteLine("Employee number: {0}", e1.Counter);
        System.Console.WriteLine("Employee name: {0}", e1.P.Name);

        Console.ReadLine();
    }
}

Upvotes: 0

Views: 49

Answers (2)

Low Flying Pelican
Low Flying Pelican

Reputation: 6054

If you modify your code like this, it will work

class Program
{
    static void Main(string[] args)
    {
        System.Console.Write("Enter number of employees: ");
        Employee.numberOfEmployees = int.Parse(System.Console.ReadLine());

        Employee e1 = new Employee();

        e.P = new Person(); //add this line

        System.Console.Write("Enter the name of the new employee: ");
        e1.P.Name = System.Console.ReadLine();

        System.Console.WriteLine("The employee information:");
        System.Console.WriteLine("Employee number: {0}", e1.Counter);
        System.Console.WriteLine("Employee name: {0}", e1.P.Name);

        Console.ReadLine();
    }
}

Upvotes: 1

nvoigt
nvoigt

Reputation: 77285

Yes, somewhere in your program you are missing the line

e1.P = new Person();

Either right in front of reading the name, or maybe in the constructor of Employee.

Upvotes: 2

Related Questions