Teaching Shaun C# Part 1: Properties

So, I have a mate named Shaun. Shaun is an avid technologist that wants to learn programming but has no one to teach him!

With me living and Joburg and him now in “The Land of Many Sorries” (Canada), I will be using this blog as a vehicle to teach my poor friend a bit about C# in a series called, “Teaching Shaun C#”. You are welcome to tag along.

Disclaimer: This is a series aimed at beginners to the C# Language like Shaun. Shaun has a little programming experience but none in C#. I will assume he has basic understanding of some common programming concepts like what classes, methods, constructors ect. If you need an explanation, ask in the comments.

Overview

OK Shaun, lets get started with something we call Properties!

Properties are essentially a way C# gives us to easily get or set a member variable of a class. In java and other languages this would be called a mutator and would be implemented using methods.

It gives us, the programmer, the control over how a variable is set.

A member variable is just a variable within scope of a class

Lets start with a Full Property:

In the below class Part1ExampleFullProperty we see a property in action for the first time. The Name property has it’s access modifier set to public, which means that code outside of the class itself can access it. 

The member variable or backing field _name, has it’s access modifier set to private. This means that code outside of the class cannot access it (they have to use the public property Name which sets it as lower case).


using NUnit.Framework;

namespace TeachingShaunCSharp
{
    public class Part1ExampleFullProperty
    {
        ///<summary>;
        ///  Our member variable (private means that we can only access this variable from within this class)
        /// &lt;/summary&gt;

        private string _name;

        ///<summary>;
        /// This Property always returns our _name variable in uppercase but sets it in lowercase
        /// </summary>;

        public string Name
        {
            get
            {
                return _name.ToUpper();
            }
            set
            {
                _name = value.ToLower();
            }
        }

        public Part1ExampleFullProperty()
        {

        }
    }

    ///<summary>;
    /// Tests are a way to (you guessed it) TEST our code.
    ///
    /// We are using NUnit to test our methods (google: "NUnit Test explorer window to see how to run your tests")
    /// </summary>;

    [TestFixture]
    public class Part1ExampleFullPropertyTests
    {
        ///<summary>;
        /// Don't worry about the test stuff, this method/function just shows the example class in action
        /// </summary>;

        [Test]
        public void NameIsReturnedInUpperCase()
        {
            var part1Example = new Part1ExampleFullProperty();

            // Set the property value
            part1Example.Name = "Shaun";

            // We can't do this because _name is private (will not compile)
            //part1Example._name = "Shaun";

            Assert.AreEqual("SHAUN", part1Example.Name);
        }
    }
}

Next, lets look at Auto Properties:

Auto properties are a shorthand way to declare a property.

In the end, it does the same as creating a backing field/variable without having to actually do it (laziness, shweet!)


using NUnit.Framework;

namespace TeachingShaunCSharp
{
    public class Part1ExampleAutoProperty
    {
        ///<summary>;
        /// This is an auto property and uses a shorthand get; set;
        /// </summary>;

        public string UserName { get; set; }

        ///<summary>;
        /// This is an auto property that has a public get but a private set.
        ///
        /// This means that it can only be set from within the class, like from the contructor
        /// </summary>;

        public int UserId { get; private set; }

        public Part1ExampleAutoProperty(int userId)
        {
            UserId = userId;
        }
    }

    [TestFixture]
    public class Part1ExampleAutoPropertyTests
    {
        [Test]
        public void CanSetUserName()
        {
            var part1Auto = new Part1ExampleAutoProperty(1);

            part1Auto.UserName = "Shaun";

            // Can't access setter of UserId
            //part1Auto.UserId = 2;// Cant do this because private set;

            Assert.AreEqual("Shaun", part1Auto.UserName);
            Assert.AreEqual(1, part1Auto.UserId);
        }
    }
}

What we have learned:

  1. Properties are a way to control access to class variables
  2. We can use Auto properties or write them out in full depending on the need
  3. public means we can access something anywhere
  4. private means that only things in our class can access something.

Things Shaun has to do to run this example:

  1. Install Visual Studio 2015 Community
  2. Download the Source code from Bitbucket and open it in Visual Studio

If you want more info on properties or anything else ask away in the comments (or Google it for God’s sake).

Luke

Advertisements

2 Comments Add yours

  1. Mr. Gaia says:

    A nice gesture of you 🙂

    PS!
    Before you start teaching him properties, maybe you should explain to him about classes an objects …?

    Like

    1. Luke Warren says:

      Thanks. I did make the disclaimer that Shaun is familiar with basic OO language constructs but might be worth doing an article on. Thanks!

      Like

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 )

Google+ photo

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

Connecting to %s