ltw
ltw

Reputation: 285

C# - simple property usage example form tutorial doesn't work

As a beginner in C# I'm looking for useful tutorials in internet. I came across this one: http://csharp.net-tutorials.com/ . I found supposedly easy example of property usage that gives unexpected result (I'm using Microsoft Visual Studio 2015). The example is taken from lesson http://csharp.net-tutorials.com/classes/properties/ and a previous lesson.

using System;
namespace Workshop
{

    class Program
    {
        static void Main(string[] args)
        {
            Car car;

            car = new Car("Red");
            Console.WriteLine(car.Describe());

            car = new Car("Green");
            Console.WriteLine(car.Describe());

            Console.ReadLine();

        }
    }

    class Car
    {
        private string color;

        public Car(string color)
        {
            this.color = color;
        }

        public string Describe()
        {
            return "This car is " + Color;
        }

    public string Color
    {
        get
        {
            return color.ToUpper();
        }
        set
        {
            if (value == "Red")
                color = value;
            else
                Console.WriteLine("This car can only be red!");
        }
    }
}

The result of this program is:

The car is RED
The car is GREEN

while I expected that the second line would be:

This car can only be red!

Can someone explain to me why this example behave like this? And more general question: does anyone know if this tutorial is a good one, or should I look for something different?

Upvotes: 0

Views: 84

Answers (2)

Julien
Julien

Reputation: 3537

The line is in the set method of Color property. In your code, you didn't call the set method of Color. If you want this line, edit your constructor :

public Car(string color)
{
   this.Color = color;
}

However, you don't set color when the string is not "Red". So, the output will be :

The car is RED
This car can only be red!

And after that, you'll get a NullReferenceException because color is null in return color.ToUpper();

Upvotes: 2

Nikita Shrivastava
Nikita Shrivastava

Reputation: 3018

You have set color (variable) in the constructor , so no validation happened because you have placed validation in set{} of Color(property). So because you are not setting Color,it never hits the setter.

Upvotes: 1

Related Questions