Joseph
Joseph

Reputation: 13

C# Console not writing object string

I'm trying to get the console to write a string that is part of a object, however the console leaves the string portion blank.

This is how i am getting the information:

Console.WriteLine("Please Enter an Agent Name: ");
agent1 = (Console.ReadLine());

Console.WriteLine("Please Enter " + agent1 + "'s Number of Customers: ");
ID1 = int.Parse(Console.ReadLine());

Then passing the variable agent 1 into a class i created:

Insurance Agent1 = new Insurance(agent1, ID1);

Then im tryting to tell the console to write out the agent's name and customer number:

Console.WriteLine("Agent 1 Name: "+ Agent1.Agent +" , Agent 1 Number of Customers: " + Agent1.Customers +".");

However, the console writes the customer number, which is an int, but not the string agent.

Please Enter an Agent Name: Test Please Enter Test's Number of Customers: 12

Agent 1 Name: , Agent 1 Number of Customers: 12.

Any idea on how to get this to work?

EDIT:

This is the insurance class for reference:

class Insurance
{
    private string _Agent; //String for _Agent because it will be a series of letters
    private int _Customers; //Int for _Customers because it will be a whole number

    public Insurance (string Agent, int Customers)
    {
        this.Agent = Agent;
        this.Customers = Customers;
    }

    public string Agent
    {
        get { return _Agent; }
        set { _Agent = Agent; }
    }

    public int Customers
    {
        get { return _Customers; }
        set //Only set _Customers if the value is larger or equal to zero, if less than zero (negative) set to zero
        {
            if (value >= 0)
            {
                _Customers = value;
            } else if (value < 0) {
                _Customers = 0;
            }
        }
    }
}

Upvotes: 1

Views: 75

Answers (1)

Grant Winney
Grant Winney

Reputation: 66449

Your "set" accessor is setup incorrectly. It's setting the value of _Agent to Agent, which calls the "get" on the property itself. The "getter" for Agent returns the _Agent field which is null.

Use value instead:

public string Agent
{
    get { return _Agent; }
    set { _Agent = value; }
}

Also, if I may, here's a few other suggestions on trimming down that class. But take it with a grain of salt, especially if you're just learning.

class Insurance
{
    private int customers;

    public Insurance(string agent, int customers)
    {
        Agent = Agent;
        Customers = Customers;
    }

    public string Agent { get; set; }

    public int Customers
    {
        get { return customers; }
        set { customers = Math.Max(value, 0); }
    }
}

Upvotes: 1

Related Questions