DynamicObject

I ran across this the other day when looking at some code from the Internet.  I hadn’t heard of DynamicObject before, so I thought I’d investigate.  The definition from MSDN states that it “Provides a base class for specifying dynamic behavior at run time. This class must be inherited from; you cannot instantiate it directly.”

You can think of it as something similar to the .NET Object class, except that it enables you to define which methods or properties can be performed at run time.

For other classes, you will get a compile time error when you’ve written code against a nonexistent method.  Classes that inherit from DynamicObject will not, but will be instead evaluated at run time.  If the dynamic class hasn’t implemented the method or coded for nonexistent methods, then a run time error will be thrown.

Here’s an example:

using System;
using System.Dynamic;

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

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {

    }
}

The MyDynamicClass inherits from DynamicObject and is completely empty.  However, the Main method is calling a method called MyAdder which sonds like it adds two integer arguments.  When this code is compiled, there’s no errors, but when we run we get a “RunTimeBinderException was unhandled error” which states that “‘DynamicObjectExample.MyDynamicClass’ does not contain a definition for ‘MyAdder’.”

To add logic for situations where a method is invoked which doesn’t exist, the TryInvokeMember method can be overridden.

using System;
using System.Dynamic;

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

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Console.WriteLine(binder.Name + "  Method not present in this  class ");
            result = 0;
            return true;
        }
    }
}

The result of the above is

“MyAdder Method not present in this class

Result: 0”

with no exceptions.  Now let’s see what happens when we actually implement the MyAdder method on MyDynamicClass.

using System;
using System.Dynamic;

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

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Console.WriteLine(binder.Name + "  Method not present in this  class ");
            result = 0;
            return true;
        }

        public int MyAdder(int x, int y)
        {
            return x + y;
        }
    }
}

The result of the above will be “Result: 3” which is what we expect :).

TryGetMember and TrySetMember are other virtual members on DynamicClass that allow you to add logic for getting and setting properties that do not exist.

Advertisements

Most Used Enumerable(T) Methods

Here’s the Enumerable methods I use the most.  All of these are available in the .NET 4.0 Framework.

Enumerable.Any() – Determines whether a sequence contains any elements.

Enumerable.Empty<T>() – Returns an empty IEnumerable<T> that has the specified type argument.

Enumerable.Distinct() – Returns distinct elements from a sequence by using the default equality comparer to compare values.

Enumerable.FirstOrDefault() – Returns the first element of a sequence, or a default value if the sequence contains no elements.

Enumerable.Count() – Returns the number of elements in a sequence.

Enumerabel.LastOrDefault() – Returns the last element of a sequence, or a default value if the sequence contains no elements.

Enumerable.Max() – Returns the maximum value in a generic sequence.

Enumerable.Min() – Returns the minimum value in a generic sequence.

Enumerable.Select() – Projects each element of a sequence into a new form.

Enumerable.ToArray() – Creates an array from a IEnumerable<T>.

Enumerable.Where() – Filters a sequence of values based on a predicate.

Here’s a link to the MSDN site that lists all the available methods

Tuple

Tuple is a new class in the .Net 4.0 framework which allows you to hold up to 8 components in a single class.  The alternative is creating a specific class with properties for each component.  This makes this class ideal for the following situations:

1.  Returning multiple values from a method without the use of out parameters

2.  Pass multiple values to a method using a single class.

3.  Collections of Tuples can be used to represent database information or array data.

4.  Easy access and manipulation of a data set.

Here’s an example using Tuple<T1, T2>

class Program
    {
        static void Main(string[] args)
        {
            int dividend, divisor;
            Tuple<int, int> result;

            dividend = 136945; divisor = 178;
            result = IntegerDivide(dividend, divisor);
            if (result != null)
                Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
                                  dividend, divisor, result.Item1, result.Item2);
            else
                Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);

            dividend = Int32.MaxValue; divisor = -2073;
            result = IntegerDivide(dividend, divisor);
            if (result != null)
                Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
                                  dividend, divisor, result.Item1, result.Item2);
            else
                Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);

            Console.ReadLine();

        }

        private static Tuple<int, int> IntegerDivide(int dividend, int divisor)
        {
            try
            {
                int remainder;
                int quotient = Math.DivRem(dividend, divisor, out remainder);
                return new Tuple<int, int>(quotient, remainder);
            }
            catch (DivideByZeroException)
            {
                return null;
            }
        }

    }

ThreadPool

I discovered this class the other day.  It’s actually been around for a while as part of the .NET 2.0 framework.  You can use it to run a method in a different thread.  Here’s a description from the MSDN site.

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. (See Using Threading for background information.) This leaves the primary thread free to perform other tasks asynchronously.

Thread pools are often employed in server applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.

Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.

Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available.

Here’s a very simple example that illustrates how the main execution thread continues without waiting for the “DoSomething” thread to complete.  ≈

    class ThreadPoolExample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start");
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething), args);

            Console.WriteLine("Finish");

            Console.ReadLine();
        }

        private static void DoSomething(object args)
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(100);
                Console.WriteLine(i);
            }
        }
    }

Here’s the output:

 

 

 

 

 

 

If we needed to know when the work was finished from Threadpool, then a ManualResetEvent could be passed into a WaitHandle like the example described here.

A Few .NET String Functions (Split, Join, IsNullOrEmpty, IsNullOrWhiteSpace)

Here’s some of my favorite String functions in .NET.

    class StringFunctions
    {
        static void Main(string[] args)
        {
            // Check for Null or Empty
            const string emptyString = "";
            if (String.IsNullOrEmpty(emptyString))
                Console.WriteLine("String is Empty or Null");

            // Join an array of integers together
            Collection array = new Collection() { 1, 2, 3 };
            Console.WriteLine(String.Join(",", array));

            // Split a string into an array
            ICollection fullStringArray = "The cat in the hat".Split(' ');
            foreach (var element in fullStringArray)
                Console.WriteLine(element);

            // Split ignoring emtpy spaces
            const string numberList = "1,2,3,4,,6";
            ICollection trimmedStringArray = numberList.Split(new[] { ',' }, numberList.Length, StringSplitOptions.RemoveEmptyEntries);
            foreach (var element in trimmedStringArray)
                Console.WriteLine(element);

            Console.ReadLine();
        }
    }

Output:

 

 

 

 

 

 

Here’s a link to an article with more examples for Split.

IsNullOrWhiteSpace is new in .NET 4.0. It’s similar to IsNullOrEmpty, but it also will catch strings that contain only empty spaces. In prior versions, you would have to trim the string prior to calling IsNullOrEmpty if you wanted to treat strings with only empty spaces as empty strings.

Action(T)

I recently discovered the Action in .NET.  It’s in version 4.0 of the .NET framework.  They’re very similar to delegates, but they require less setup.

Type Parameters

in T
The type of the parameter of the method that this delegate encapsulates. 

This type parameter is contravariant. That is, you can use either the type you specified or any type that is less derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.

Parameters

obj
Type: T
The parameter of the method that this delegate encapsulates.

Click here for the complete definition with more examples from the MSDN Library.

Here’s an example:

    class ActionExample1
    {
        static void Main(string[] args)
        {
            List<String> names = new List<String>();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");

            // Display the contents of the list using the Print method.
            ShowOutput(names, Print);
        }

        private static void ShowOutput(List<String> argument, Action<string> action)
        {
            foreach (var arg in argument)
            {
                action(arg);
            };
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }

Output:

You can also assign a lambda expression to an Action<T> delegate instance, as the following example illustrates.

    class ActionExampleLamda
    {
        static void Main3(string[] args)
        {
            Action<string> messageTarget;

            // Display the contents of the list using the Print method.
            messageTarget = s => Print(s);

            messageTarget("Hello World");
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }

Here’s another example that utilizes the ForEach directly on the collection which takes an Action as an argument.

    class ActionExample2
    {
        static void Main2(string[] args)
        {
            List names = new List();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");

            // Display the contents of the list using the Print method.
            names.ForEach(Print);
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }

Persisting Dates and Numbers using CultureInfo.InvariantCulture

When persisting a date as a string, it is a good idea to use the invariant culture to format it—this ensures that a consistent format is always used internally, regardless of the culture used for presenting dates to the user.

Example:

string dateToSave = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture);

In addition, the InvariantCulture is useful for storing data that will not be displayed directly to end users. Storing data in a culture-independent format guarantees a known format that does not change.

For example, screen coordinates are generally serialized as a comma-delimited list (x, y). If these coordinates are not serialized/de-serialized using an invariant culture, depending on the current UI culture, the list separator could end up being a semi-colon and as a result will not be valid as screen coordinates and will cause a system exception.

Just remember, when storing formatted numbers or dates in files, using InvariantCulture is the best option.