Search code examples
c#.netconsole.writeline

Console not writing class object name


C# in Visual Studio... very simple main and class method. When running, my program only reads out "Hi friend", and not "Otis". Any ideas to what's going on?

using System;

namespace Project
{
    class Program
    {
        static void Main(string[] args)
        {       
            Console.WriteLine("Hi friend");        
            Cow myCow = new Cow("Otis");
            Console.WriteLine(myCow.Name);
        }
    }
    
    class Cow
    {
        public string Name { get; set; }
        public Cow(string name)
        {
            name = Name;
        }   
    }
}

Solution

  • You have the assignment in the constructor reversed - you're assigning the (empty) member Name to the argument name, instead of the other way round:

    class Cow
    {
        public string Name { get; set; }
        public Cow(string name)
        {
            Name = name;
        }   
    }
    

    Note - using this would make it more explicit, and easier to catch such mistakes:

    class Cow
    {
        public string Name { get; set; }
        public Cow(string name)
        {
            this.Name = name;
        }   
    }