Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does applying a Rename Method to change a name with get/set in c# work?

I have been doing an assignment recently but remain stuck/confused as to how the get/set property works. I have read a lot but can't seem to find what I am looking for.
The following code is from the assignment:

        Animal cat = new Animal("Epicat");
        cat.WhoAmI(); //Displays "I am an animal !"
        cat.Describe(); //Displays "My name is Epicat."
        cat.Name = "Moumoune"; //Doesn't work
        cat.Rename("Moumoune"); //Changes the name
        cat.Name; //return "Moumoune"

This is what I have coded so far:
(Ignore the throw new exceptions.)

public class Animal
{
    private string name;

    public string Name
    {
        get { return name;  }
        set { name = value; }
    }

    #region Constructor

    public Animal(string name)
    {
        this.name = name;
        //throw new TargetInvocationException(new InvalidOperationException("Constructor is not implemented yet"));
    }

    #endregion Constructor

    #region Methods

    public virtual void WhoAmI()
    {
        Console.WriteLine("I am an animal !");
        //throw new NotImplementedException("Please fix this quickly");
    }

    public virtual void Describe()
    {
        Console.WriteLine("My name is {0}.", name);
        //throw new NotImplementedException("Please fix this quickly");
    }

    public void Rename(string NewName)
    {
        name = NewName;
        //throw new NotImplementedException("Please fix this quickly");
    }

    #endregion Methods
}

I don't comprehend how the cat.Name = "Moumoune" doesn't edit (according to the assignment) the get/set name and why it wouldn't work.
And why would cat.Rename and cat.Name change anything?

like image 622
Kai.G Avatar asked Nov 28 '25 11:11

Kai.G


1 Answers

I think, what meant is - you can't assign through Name property. This is achieavable through simple omittion of unneeded setter:

public class Animal
{
    private string name;

    public string Name
    {
        get { return name;  }
        //set { name = value; } just comment it out
    }

    public Animal(string name)
    {
        this.name = name;
    }

    public virtual void WhoAmI()
    {
        Console.WriteLine("I am an animal !");
    }

    public virtual void Describe()
    {
        Console.WriteLine("My name is {0}.", name);
    }

    public void Rename(string NewName)
    {
        name = NewName;
    }
}

So, this will not even compile:

var a = new Animal("foo");
a.Name = "bar";

If you want for it to compile, but don't do a thing....just don't do a thing:

public class Animal
{
    private string name;

    public string Name
    {
        get { return name;  }
        set { /*name = value;*/ } //just don't do a thing.
    }

    public Animal(string name)
    {
like image 140
eocron Avatar answered Nov 30 '25 01:11

eocron