[c#] C# Get/Set Syntax Usage

These are declarations for a Person class.

protected int ID { get; set; }
protected string Title { get; set; }
protected string Description { get; set; }
protected TimeSpan jobLength { get; set; }

How do I go about using the get/set? In main, I instantiate a

Person Tom = new Person();

How does Tom.set/get??

I am use to doing C++ style where you just write out the int getAge() and void setAge() functions. But in C# there are shortcuts handling get and set?

This question is related to c# syntax properties

The answer is


You are not able to access those properties as they are marked as protected meaning:

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.


Set them to public. That is, wherever you have the word "protected", change it for the word "public". If you need access control, put it inside, in front of the word 'get' or the word 'set'.


I do not understand what this is unclear

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.

In this example, the class TimePeriod stores a time period. Internally the class stores the time in seconds, but a property called Hours is provided that allows a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}

Properties Overview

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.

The value keyword is used to define the value being assigned by the set indexer.

Properties that do not implement a set method are read only.

http://msdn.microsoft.com/en-US/library/x9fsa0sw%28v=vs.80%29.aspx


These are properties. You would use them like so:

Tom.Title = "Accountant";
string desc = Tom.Description;

But considering they are declared protected their visibility may be a concern.


Assuming you have a song class (you can refer below), the traditional implementation would be like as follows

 class Song
  {
       private String author_name;
       public String setauthorname(String X) {}; //implementation goes here
       public String getauthorname() {}; //implementation goes here
  }

Now, consider this class implementation.

      class Song 
      {
            private String author_name;
            public String Author_Name
            { 
                 get { return author_name; }
                set { author_name= value; }
             }
      }

In your 'Main' class, you will wrote your code as

    class TestSong
    { 
      public static void Main(String[] Args)
      {
          Song _song = new Song(); //create an object for class 'Song'    
          _song.Author_Name = 'John Biley';
          String author = _song.Author_Name;           
          Console.WriteLine("Authorname = {0}"+author);
      }
    }

Point to be noted;

The method you set/get should be public or protected(take care) but strictly shouldnt be private.


By the way, in C# 3.5 you can instantiate your object's properties like so:

Person TOM=new Person 
{ 
   title = "My title", ID = 1 
};

But again, properties must be public.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to properties

Property 'value' does not exist on type 'EventTarget' How to read data from java properties file using Spring Boot Kotlin - Property initialization using "by lazy" vs. "lateinit" react-router - pass props to handler component Specifying trust store information in spring boot application.properties Can I update a component's props in React.js? Property getters and setters Error in Swift class: Property not initialized at super.init call java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US How to use BeanUtils.copyProperties?