Creating Your Own Custom Dynamic C# Classes

C# provides pre-supplied dynamic types such as the ExpandoObject. It is also possible to create new dynamic types or add dynamic capabilities to existing custom classes.

One of the core interfaces that enables dynamic behaviour is the IDynamicMetaObjectProvider interface. Whilst this interface can be implemented, an easier way to create a custom dynamic class is to inherit from DynamicObject class.

The DynamicObject base class provides a number of virtual methods that allow an instance of the derived class to respond to dynamic operations such as getting or setting the value of a dynamically added property or invocation of a dynamic method.

The following simple example allows adding of arbitrary dynamic properties at runtime. The class overrides the TrySetMember and TryGetMember virtual methods to provide the behaviour. Notice that these methods have a binder parameter that gives information about the dynamic operation that is being attempted, such as the name of the property (binder.Name). Also note that the methods return a Boolean value to indicate to the runtime whether the dynamic operation succeeded.

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

namespace CustomDynamic
{
    class MyDynamicClass : DynamicObject
    {
        private readonly Dictionary<string, object> _dynamicProperties = new Dictionary<string, object>(); 

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            _dynamicProperties.Add(binder.Name, value);

            // additional error checking code omitted

            return true;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            return _dynamicProperties.TryGetValue(binder.Name, out result);
        }

        public override string ToString()
        {
            var sb = new StringBuilder();

            foreach (var property in _dynamicProperties)
            {
                sb.AppendLine($"Property '{property.Key}' = '{property.Value}'");
            }

            return sb.ToString();
        }
    }
}

At runtime, if the instance of the class is declared as dynamic, arbitrary properties can be set as the following simple console application demonstrates:

using System;

namespace CustomDynamic
{
    class Program
    {
        static void Main(string[] args)
        {            
            dynamic d = new MyDynamicClass();

            // Need to declare as dynamic, the following cause compilation errors:
            //      MyDynamicClass d = new MyDynamicClass();
            //      var d = new MyDynamicClass();

            // Dynamically add properties
            d.Name = "Sarah"; // TrySetMember called with binder.Name of "Name"
            d.Age = 42; // TrySetMember called with binder.Name of "Age"

            Console.WriteLine(d.Name); // TryGetMember called
            Console.WriteLine(d.Age); // TryGetMember called

            Console.ReadLine();
        }
    }
}

To learn more about how C# makes dynamic possible, some potential use cases, and more detail on implementing custom types check out my Dynamic C# Fundamentals Pluralsight course.

You can start watching with a Pluralsight free trial.

SHARE:

New Pluralsight Course: Dynamic C# Fundamentals

My Pluralsight course “Dynamic C# Fundamentals” is now available.

The course is split into 4 modules:

Module 1 introduces the dynamic features of C# and how it is enabled by the Dynamic Language Runtime (DLR).

Module 2 looks at numerous places that dynamic C# can be used including COM, XAML, MVC, and JSON.

Module 3 digs into more detail and shows how to create custom C# classes that can exhibit dynamic behaviour.

Module 4 shows how the DLR enables C# to interoperate with other dynamic languages such as IronPython.

Full list of topics:

1 Introducing Dynamic C#

  • Why Dynamic C#?
  • Course Outline
  • Introducing the DLR
  • Static and Dynamic Binding
  • Dynamic Binding in Action and RuntimeBinderException
  • Implicit Dynamic Conversions
  • Var and Dynamic
  • Runtime Method Resolution
  • Dynamic and Object Types
  • Limitations of Callable Methods
  • Introducing ExpandoObject
  • Refactoring to Dynamic
  • Dynamically Adding ExpandoObject Behavior

2 Simplifying Code with Dynamic C#

  • Simplifying Reflection Code
  • Reducing Code with Unified Numeric Methods
  • COM Interop Without Interop Assemblies
  • Reducing Plumbing Code with Dynamic JSON
  • Dynamically Populating Excel with Arbitrary JSON Data
  • Dynamic JSON in Web API
  • ExpandoObject and XAML Databinding
  • Dynamic SQL Query Results with Dapper
  • Improving SpecFlow Test Code with Dynamics
  • Dynamic Code Considerations

3 Creating Custom Dynamic Classes

  • Why Custom Dynamic Classes?
  • The IDynamicMetaObjectProvider Interface
  • The DynamicObject Base Class
  • Creating a Dynamic HtmlElement Class
  • Creating the First Test
  • Adding Initial Dynamic Capabilities
  • Dynamic Operation Exceptions
  • Improving the Debugger Experience
  • Overriding ToString
  • Implementing Additional Interfaces
  • Making the Dynamic Object Enumerable
  • Implementing Dynamic Methods
  • Method Invocation Precedence
  • Invoking the Dynamic Object Itself

4 Interoperating with Dynamic Languages

  • Why Dynamic Interop?
  • Getting Started with IronPython
  • Getting Scripting Input from the User
  • Scripting Risks
  • Executing Python Statements
  • Interacting with Python Objects
  • Passing Custom Dynamic Objects to Python

Check out the full course description.

You can start watching with a Pluralsight free trial.

SHARE:

Writing Implicit and Explicit C# Conversion Operators

When writing custom classes we can provide behaviour to allow for both explicit and implicit conversions to other types.

Implicit conversion operators are those that don’t require an explicit cast.

Explicit conversion operators are those that do require an explicit cast.

As an example, the following code shows a simple console application to covert a weight in Pounds to Kilograms.

internal class Program
{
    private static void Main(string[] args)
    {
        WriteLine("Please enter a value in lbs");
        var lbsText = ReadLine();

        var lbs = new PoundsExplicit(float.Parse(lbsText));
        WriteLine($"\nYou entered {lbs}");

        Kilogram kg = (Kilogram) lbs;
        WriteLine($"\n{lbs} is {kg}");

        WriteLine("\nPress enter to exit");
        ReadLine();
    }
}

Notice in the preceding code the line Kilogram kg = (Kilogram) lbs; is explicitly casting from a type of PoundsExplicit to Kilograms.

The Kilogram class is defined as follows:

internal class Kilogram
{
    public float Weight { get; set; }

    public Kilogram(float weight)
    {
        Weight = weight;
    }

    public override string ToString()
    {
        return $"{Weight} kg";
    }
}

To allow the (explicit) cast from PoundsExplicit to Kilogram, the PoundsExplicit class defines an explicit conversion operator as shown in the following code:

internal class PoundsExplicit
{
    public float Weight { get; set; }

    public PoundsExplicit(float weight)
    {
        Weight = weight;
    }
    public override string ToString()
    {
        return $"{Weight} lbs";
    }

    public static explicit operator Kilogram(PoundsExplicit lbs)
    {
        const float conversionRate = 0.45359237f;

        float equivalentKgs = lbs.Weight * conversionRate;

        return new Kilogram(equivalentKgs);
    }
}

To allow the conversion to Kilogram to be implicit, with no cast required (e.g. Kilogram kg = lbs;) the operator can be changed to implicit as shown in the following class:

internal class PoundsImplicit
{
    public float Weight { get; set; }

    public PoundsImplicit(float weight)
    {
        Weight = weight;
    }       

    public override string ToString()
    {
        return $"{Weight} lbs";
    }

    public static implicit operator Kilogram(PoundsImplicit lbs)
    {
        const float conversionRate = 0.45359237f;

        float equivalentKgs = lbs.Weight * conversionRate;

        return new Kilogram(equivalentKgs);
    }
}

The main method can now be modified as follows:

private static void Main(string[] args)
{
    WriteLine("Please enter a value in lbs");
    var lbsText = ReadLine();

    var lbs = new PoundsImplicit(float.Parse(lbsText));
    WriteLine($"\nYou entered {lbs}");

    Kilogram kg = lbs;
    WriteLine($"\n{lbs} is {kg}");

    WriteLine("\nPress enter to exit");
    ReadLine();
}

Notice in the preceding code the conversion from PoundsImplicit to Kilogram now is implicit, it does not require an explicit cast.

When deciding between implicit or explicit conversion operators you should consider the resulting readability of code that uses the types. An implicit cast is more convenient whereas an explicit cast may add extra clarity/readability to the code that uses the types.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

New FeatureToggle Release: v3.4 With Fluent Syntax

FeatureToggle is an open source feature toggling / feature switching library for .NET.

Version 3.4 Introduces an new additional way to get the value of whether a toggle is enabled or not.

In versions to v3.3 and earlier, to get the value of a toggle, an instance of the toggle class needed to be created manually:

new SampleFeatureToggle().FeatureEnabled

With v3.4 a new additional fluent way is introduced to improve readability and offer a convenience when evaluating a toggle.

First reference the FeatureToggle.Core.Fluent namespace, then the Is<T> class can be used as follows:

Is<SampleFeatureToggle>.Enabled
Is<SampleFeatureToggle>.Disabled

To make the fluent style a little more readable, the name of the concrete toggle class can be shorted, so rather than PrintFeatureToggle for example, it could be named Print, the code would then read:

Is<Printing>.Enabled
Is<Printing>.Disabled

SHARE:

New Pluralsight Course: Automated Business Readable Web Tests with Selenium and SpecFlow

SpecFlow is a tool that can translate natural language scenarios (e.g. writing in English or other spoken languages) into test code. This can allow business people, users, or other stakeholders to verify that the correct features are being built.

Selenium is a tool that allows test code (multiple programming languages supported) to automated a web browser. This allows the creation of automated UI tests that operate the web application as if an end user where doing it; for example clicking buttons and typing text into input boxes.

My new Pluralsight course shows how to integrate these two tools.

The course is organized into four modules:

  1. Introduction to Business Readable Web Testing
  2. Getting Started with Selenium
  3. Adding Business Readability with SpecFlow
  4. Creating More Maintainable Web Automation

If you’re new to SpecFlow I suggest watching this course first before moving on to Automated Business Readable Web Tests with Selenium and SpecFlow.

You can start watching with a Pluralsight free trial.

SHARE:

Free eBook C# 6.0: What’s New Quick Start Complete

free C# bok cover image

My new free eBook “C# 6.0: What’s New Quick Start” is now complete and available for download.

The book covers the following:

  • Using Static Type Directive
  • String Interpolation
  • The Null-Conditional Operators
  • Getter Only Auto Properties
  • Using Await in Catch and Finally Blocks
  • Property, Dictionary, and Index Initializers
  • The nameof Operator
  • Expression Bodied Functions and Properties
  • Exception Filters
  • Visual Studio 2015 and C# 6

You can download it for free or pay what you think it is worth.

Happy reading!

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

New Pluralsight Course: Business Readable Automated Tests with SpecFlow 2.0

My newest Pluralsight course was just published. Business Readable Automated Tests with SpecFlow 2.0 teaches how to create tests that the business can read, understand, and contribute to. These “English-like” tests (other spoken languages are supported) can be executed by writing test code that is associated with the “English-like” steps. Because the tests sit alongside the source code, they can become living (executable) documentation for the system, as opposed to an out-of-date Word document somewhere on the network for example. Check out the course here.

You can start watching with a Pluralsight free trial.

SHARE:

New Free eBook C# 6.0: What’s New Quick Start

C# 6 eBook Cover Image

The first chapters of my new free eBook have just been published.

The book will cover the new features added in C# 6.0 and provide a quick start to those new to version 6 or as a handy reference to those already using C# 6.0

New chapters are being added periodically and you can get the version now and get access to new chapters as they are published.

You can download the book for free or pay what you think it’s worth.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

FeatureToggle v3.3 Released

FeatureToggle is an open source feature toggling library for .NET.

Version 3.3 was just released to NuGet and includes two minor new features as described below.

FallbackValueDecorator

The FallbackValueDecorator allows you to wrap (decorate) a primary toggle and specific a fallback toggle to be used if the primary toggle fails or is not configured.

new FallbackValueDecorator(new MyPrimaryToggle(), new MyFallbackToggle());

An optional overload allows the specifying of an Action<Exception> to be called if the primary toggle errors for example to perform some logging or alerting:

public FallbackValueDecorator(IFeatureToggle primaryToggle, IFeatureToggle fallbackToggle, Action<Exception> logAction = null)

CompositeOrDecorator

The CompositeOrDecorator allows the specification of two toggle instances, if either one of the toggles is enabled the decorator will return true:

new CompositeOrDecorator(new AnEnabledFeature(), new ADisabledFeature());


If you’re new to the concept of feature toggling or FeatureToggle check out my Pluralsight course Implementing Feature Toggles in .NET with FeatureToggle or the documentation.


Thanks to Craig Vermeer for the work investigating failing convention tests in VS2015 for this release.

SHARE:

New Pluralsight Course: Getting Started Building Windows Services with Topshelf

My newest Pluralsight course “Getting Started Building Windows Services with Topshelf” has just been released.

Topshelf is an open source library that makes it easier to develop, test, and install Windows Services.

If you’re new to Windows Services, the course starts by introducing how Windows Services work and some of their features such as automatic service recovery and the ability to run in the background as different users.

The course then goes on to cover how to create a Windows Service with Topshelf as well as additional techniques such as debugging, logging, pause and continue and the ability to send custom commands to running services.

Check out the course link or browse all my Pluralsight courses.

You can start watching with a Pluralsight free trial.

SHARE: