C# Workshop – Properties & Access


Properties & Access

Programmes can already have Variables but it’s also possible to have Properties which is a flexible way or reading, writing or computing the value of another field and allows data to be accessed easily. This other field may be set up as private which is an Access modifier which means it can only be set or read within the same class they are contained within.

If is then possible to create a public property which can be accessed from anywhere that uses this private field and do something different with that Variable, you can do this in dotnetfiddle.net by entering the following:

using System;

namespace Workshop
	public class Demo
		private static double _seconds = 0;
		public static double Minutes
			get { return _seconds / 60; }
			set { _seconds = value * 60; }
		public static void Main()
			Minutes = 15;
			Console.WriteLine("Minutes:" + Minutes);
			Console.WriteLine("Seconds:" + _seconds);

In this example, the Variable or Member _seconds is declared as private it is also using the static keyword as the method it is being called from is also static, the Property Minutes is declared as public so can save the Minutes value into seconds using the Property.

When declaring private members for properties you can name them with an underscore in front so you know they’ll be private and usually not used directly. When declaring a public Property these usually begin with a capital letter and when using multiple words each word should be capitalised – this is known as Camel Case.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s