Category Archives: C#

Create instance without invoking constructor

It is not always true that constructors will be invoked when constructing an object. I actually stumbled today wondering why the no argument constructor was not invoked when deserializing object from XML using Java XStream library, and after doing some search found that there are ways to create object without calling the constructor. I wouldn’t say this is a good practice especially when we are not writing library code, but just a reminder that some code may work like this, so when dealing with object deserialization, we need to be very careful on checking whether our fields are initialized.

Continue reading

Referencing local variable in anonymous delegates

In C#, anonymous delegates, or lambda expressions, which ultimately is compiled into delegates, are able to access parent context, i.e. accessing variables that is not passed in as an argument. Here I am summarizing the most common cases:

  • Referencing constants
class Program
{
    public void Demo()
    {
        const string message = "Hello, World!";

        var displayMessage = new Action(() => Console.WriteLine(message));

        displayMessage.Invoke();
    }

    private static void Main(string[] args)
    {
        new Program().Demo();
    }
}

In this scenario, the message is defined as constant. After compiler optimization, we can see it is creating a static delegate field in Demo.Program class, linking to a static method b__0. In the static method, the message is directly loaded as a string.

referencing-local-variable-in-anonymous-delegates-1

Continue reading

PropertyInfo selector using Lambda expressions

Considering the Type.GetProperty() method provided in System.Reflection, it takes a string parameter. If we are writing frameworks, this is often fine as the hard coded strings are usually self contained, and won’t be exposed to developers that users our framework. While what if we need to provide a function for those developers that uses our library to specify a property? In this case, strings may not be the best solution. Simply taking one scenario, if the property is refactored to a new name, and the string isn’t changed, then the property won’t be found using the old name.

The following example is trying to provide a way to get a PropertyInfo based on an expression. Comparing to directly using Type.GetProperty() method, this type safe, and the expression will change when the property is refactored.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
 
namespace Demo
{
    public static class PropertySelector
    {
        public static PropertyInfo GetPropertyInfo<T>(this T obj, Expression<Func<T, object>> selector)
        {
            if (selector.NodeType != ExpressionType.Lambda)
            {
                throw new ArgumentException("Selector must be lambda expression", "selector");
            }
 
            var lambda = (LambdaExpression) selector;
 
            var memberExpression = ExtractMemberExpression(lambda.Body);
 
            if (memberExpression == null)
            {
                throw new ArgumentException("Selector must be member access expression", "selector");
            }
 
            if (memberExpression.Member.DeclaringType == null)
            {
                throw new InvalidOperationException("Property does not have declaring type");
            }
 
            return memberExpression.Member.DeclaringType.GetProperty(memberExpression.Member.Name);
        }
 
        private static MemberExpression ExtractMemberExpression(Expression expression)
        {
            if (expression.NodeType == ExpressionType.MemberAccess)
            {
                return ((MemberExpression) expression);
            }
 
            if (expression.NodeType == ExpressionType.Convert)
            {
                var operand = ((UnaryExpression) expression).Operand;
                return ExtractMemberExpression(operand);
            }
 
            return null;
        }
    }
}

Continue reading