NetInverse Developers Blog

April 4, 2009
Category: .Net — Tags: , , , , — admin @ 5:23 pm

Following utility function EnumToArray takes an enum type and returns an array populated with each enum item. You can tweak the code a little bit to make the function to be EnumToList easily.

The sample code also demonstrates how to use Enumerable.Except to get the delta of two arrays of same type T.

using System;
using System.Collections.Generic;
using System.Linq;

namespace IEnumerableTest
{
    public static class Utils
    {
        public static T[] EnumToArray<T>()
        {
            Type enumType = typeof(T);
            if (enumType.BaseType != typeof(Enum))
            {
                throw new ArgumentException("T must be a System.Enum");
            }
            return (Enum.GetValues(enumType) as IEnumerable<T>).ToArray();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Convert Enum type to an array
            RoleType[] allRoles = Utils.EnumToArray();

            //Use IEnumerable.Except to get part of the array.
            RoleType[] localUserRoles = new RoleType[] { RoleType.LocalAdmin, RoleType.LocalUser, RoleType.Guest };

            RoleType[] domainUserRoles = allRoles.Except(localUserRoles).ToArray();
        }

        enum RoleType
        {
            DomainAdmin,
            LocalAdmin,
            DomainUser,
            LocalUser,
            Guest
        }
    }
}
March 9, 2009
Category: .Net — Tags: , , — admin @ 12:16 am

Following code doesn’t compile:

    class GenericFactory where T : new()
    {
        public T Create(object a, object b)
        {
            return new T(a, b);
        }
    }

The compiler will give you following error message: “‘T’: cannot provide arguments when creating an instance of a variable type.”. Well, there are a couple ways to solve this issue.

Use reflection

    class GenericFactory
    {
        public T Create(object a, object b)
        {

            return (T) typeof(T).GetConstructor(
   new System.Type[] { typeof(object), typeof(object) }).Invoke(new object[] {a, b});
        }
    }

Use intialization

Following code uses an initialization interface to solve this issue. You can also use properties instead of a method.

    interface I
    {
        void Initialize(object a, object b);
    }

    class GenericFactory where T : I, new()
    {
        public T Create(object a, object b)
        {
            T t = new T();
            t.Initialize(a, b);
            return t;
        }
    }

©2009 NetInverse. All rights reserved. Powered by WordPress