C#: 25-Class get/set

  • using getter/setters allows for logic to be used in the process
  • for gets, null checking can be performed for Singleton Design Patterns or different things can be returned based on state/value.
  • for sets, null checking & data validation can be performed on the incoming values

Object Instantiation with Property Sets

See Also: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

When an object is instantiated, the values can be set in the same statement

Car myCar = new Car{Type="Honda",Price=15000};

 

Class Logic

using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns2016
{
    public class UsingProperties
    {
        private string _name = "default";
        private Thingy _thingy;

        // set allows for validation logic(set)
        public string Name
        {
            get { return _name; }
            set {
                var formattedName = value?.Trim();
                _name = formattedName;
            }
        }

        //get allows for lazy loading a 'Thingy' object using the getter
        // used for Singleton Design Pattern
        public Thingy AThingy
        {
            get
            {
                if (_thingy == null)
                {
                    _thingy = new Thingy();
                }
                return _thingy;
            }
            set { _thingy = value; }
        }

    }

    public class Thingy {
        public string Name = "Thingy.Name";
        public string Value = "Thingy.Value";
    }

}

 

Unit Test

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace DesignPatterns2016.Tests
{
    [TestClass]
    public class UsingPropertiesTests
    {
        [TestMethod]
        public void TestingThingyGet()
        {
            //Assert.AreSame(Using)
            UsingProperties up = new UsingProperties();
            var thingy = up.AThingy;
            thingy.Name = "NEWNAME";
            thingy.Value = "NEWVALUE";
            Console.WriteLine($"Thingy Name=\"{thingy.Name}\", Thingy Value: \"{thingy.Value}\"");
            Assert.AreSame(up.AThingy, up.AThingy);

            var thingy2 = up.AThingy;
            Assert.AreSame(thingy, thingy2);
        }
    }
}

 

Output

Thingy Name="NEWNAME", Thingy Value: "NEWVALUE"

 

 

Tags