Search code examples
c#getattributesset

Cannot implicitly convert type 'Address' to 'String' in setter


As in the title I try to make setter to Adress but I got this convert error . Its code of my Worker class .

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace MAS_MP1
    {
        class Worker
        {
            string name, surname;
            protected string adress;
            int phoneNumber;
            string birthDate;

            Worker(String name, String surname, String adress, int phoneNumber, string birthDate)
            {
                this.name = name;
                this.surname = surname;
                this.adress = adress;
                this.phoneNumber = phoneNumber;
                this.birthDate = birthDate;

            }

           static List<Worker> list = new List<Worker>();

            public  static void add(Worker p)
            {
                list.Add(p);
            }
            public void setA(Adress a)
            {
                this.adress = a;
            }
            public static  void showExtension()


 {
            Console.WriteLine("Class Extesion");
            foreach (Worker p in list)
            {
                Console.WriteLine(p);
            }
            Console.ReadLine();

        }
        override
        public string ToString()
        {
            return "Name " + name + " Surname " + surname;
        }

        public static void Main(string[] args)
        {
            Worker p = new Worker("Tom,","Smith","NewStreet 8 London",123456,"12-12-2012");
            Adress a = new Adress("NewStreet" , 9 , "London");
            add(p);
            showExtension();


        }
    }
}

And error was here :

public void setA(Adress a)
        {
            this.adress = a;
        }

I try to make a complex attribute so j make second class Adress only with constructor and toString override method. Adress got street , homeNumber and cityName attributes.


Solution

  • How could this possibly work? You're trying to store an instance of Adress in a string...

    protected string adress;
    
    public void setA(Adress a)
    {
        this.adress = a;
    }
    

    There's a couple fixes.

    You could change the type of the field you're storing the value in:

    protected Adress adress;
    

    and change the constructor to accept an Adress as well:

    Worker(String name, String surname, Adress adress, int phoneNumber, string birthDate)
    

    Alternatively, modify your setter so you're storing a string:

    public void setA(Adress a)
    {
        this.adress = a.ToString();
    }