Search code examples
c#.netoutputgettersetter

Why doesn't return getter like in Java (C#)


I want to move from Java to C# and I want to try getter and setter like in Java

internal class Person
    {
 
        internal string name;
        

        internal void setName (string name)
        {
            this.name = name;   
        }

        internal string getName ()
        {
            return this.name;
        }

    }

in main:

Person alex = new Person();
alex.setName("alex");
Console.WriteLine(alex.getName);

and the output is:

System.Func`1[System.String]

Why doesn't display the expected "alex" ?


Solution

  • Because getName is a function, and not a getter. So your code should be

    Console.WriteLine(alex.getName());
    

    If you want to use setter and getters, the syntax is

    internal class Person
    {
      internal string name;
      internal string Name 
      {
        set { this.name = value; }
        get { return this.name; }
      }
    }
    

    Or more compact

    internal class Person
    {
      internal string Name { get; set; }
    }