Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8704389
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T03:05:39+00:00 2026-06-13T03:05:39+00:00

I tried to implement Jon Skeet’s solution for this question posted on this blog

  • 0

I tried to implement Jon Skeet’s solution for this question posted on this blog post to substitute the SetValue method with a non-reflection method using delegates.

The difference from the solution in the blog post is that SetValue is void, and I get the The type 'System.Void' may not be used as a type argument. exception at the line MethodInfo miConstructedHelper = miGenericHelper.MakeGenericMethod(typeof(G), pMethod.GetParameters()[0].ParameterType, pMethod.ReturnType);.

Here’s my implementation of the MagicMethod:

public class Instantiator<T> where T : new()
{
    private T instance;
    private IDictionary<string, PropertyInfo> properties;

    private Func<PropertyInfo, object, object> _fncSetValue;

    public Instantiator()
    {
        Type type = typeof(T);
        properties = type.GetProperties().GroupBy(p => p.Name).ToDictionary(g => g.Key, g => g.ToList().First());

        MethodInfo miSetValue = typeof(PropertyInfo).GetMethod("SetValue", new Type[] { typeof(object), typeof(object), typeof(object[]) });
        _fncSetValue = SetValueMethod<PropertyInfo>(miSetValue);
    }

    public void CreateNewInstance()
    {
        instance = new T();
    }

    public void SetValue(string pPropertyName, object pValue)
    {
        if (pPropertyName == null) return;
        PropertyInfo property;
        if (!properties.TryGetValue(pPropertyName, out property)) return;
        TypeConverter tc = TypeDescriptor.GetConverter(property.PropertyType);

        //substitute this line
        //property.SetValue(instance, tc.ConvertTo(pValue, property.PropertyType), null);
        //with this line
        _fncSetValue(property, new object[] { instance, tc.ConvertTo(pValue, property.PropertyType), null });
    }

    public T GetInstance()
    {
        return instance;
    }

    private static Func<G, object, object> SetValueMethod<G>(MethodInfo pMethod) where G : class
    {
        MethodInfo miGenericHelper = typeof(Instantiator<T>).GetMethod("SetValueMethodHelper", BindingFlags.Static | BindingFlags.NonPublic);
        MethodInfo miConstructedHelper = miGenericHelper.MakeGenericMethod(typeof(G), pMethod.GetParameters()[0].ParameterType, pMethod.ReturnType);
        object retVal = miConstructedHelper.Invoke(null, new object[] { pMethod });
        return (Func<G, object, object>) retVal;
    }

    private static Func<TTarget, object, object> SetValueMethodHelper<TTarget, TParam, TReturn>(MethodInfo pMethod) where TTarget : class
    {
        Func<TTarget, TParam, TReturn> func = (Func<TTarget, TParam, TReturn>)Delegate.CreateDelegate(typeof(Func<TTarget, TParam, TReturn>), pMethod);
        Func<TTarget, object, object> retVal = (TTarget target, object param) => func(target, (TParam) param);
        return retVal;
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T03:05:41+00:00Added an answer on June 13, 2026 at 3:05 am

    You are using Func in your code. Func is for methods that have a return type. For methods that return void you need to use Action.


    Your code needs to look like this:

    public class Instantiator<T> where T : new()
    {
        private T instance;
        private IDictionary<string, PropertyInfo> properties;
    
        private Action<PropertyInfo, object, object, object> _fncSetValue;
    
        public Instantiator()
        {
            Type type = typeof(T);
            properties = type.GetProperties()
                             .GroupBy(p => p.Name)
                             .ToDictionary(g => g.Key, g => g.ToList().First());
    
            var types = new Type[] { typeof(object), typeof(object),
                                     typeof(object[]) };
            var miSetValue = typeof(PropertyInfo).GetMethod("SetValue", types);
            _fncSetValue = SetValueMethod<PropertyInfo>(miSetValue);
        }
    
        public void CreateNewInstance()
        {
            instance = new T();
        }
    
        public void SetValue(string pPropertyName, object pValue)
        {
            if (pPropertyName == null) return;
            PropertyInfo property;
            if (!properties.TryGetValue(pPropertyName, out property)) return;
            TypeConverter tc = TypeDescriptor.GetConverter(property.PropertyType);
    
            var value = tc.ConvertTo(pValue, property.PropertyType);
            _fncSetValue(property, instance, value, null);
        }
    
        public T GetInstance()
        {
            return instance;
        }
    
        private static Action<G, object, object, object> SetValueMethod<G>(MethodInfo pMethod) where G : class
        {
            var miGenericHelper = 
                typeof(Instantiator<T>).GetMethod("SetValueMethodHelper", 
                                                  BindingFlags.Static | 
                                                  BindingFlags.NonPublic);
    
            var parameters = pMethod.GetParameters();
            var miConstructedHelper = miGenericHelper.MakeGenericMethod(typeof(G), 
                                          parameters[0].ParameterType,
                                          parameters[1].ParameterType,
                                          parameters[2].ParameterType);
    
            var retVal = miConstructedHelper.Invoke(null, new object[] { pMethod });
            return (Action<G, object, object, object>) retVal;
        }
    
        private static Action<TTarget, object, object, object> SetValueMethodHelper<TTarget, TParam1, TParam2, TParam3>(MethodInfo pMethod) where TTarget : class
        {
            var func = (Action<TTarget, TParam1, TParam2, TParam3>)Delegate.CreateDelegate(typeof(Action<TTarget, TParam1, TParam2, TParam3>), pMethod);
            Action<TTarget, object, object, object> retVal =
                (target, param1, param2, param3) => 
                    func(target, (TParam1) param1, (TParam2) param2, (TParam3) param3);
    
            return retVal;
        }
    }
    

    As you don’t want to call arbitrary methods like Jon Skeet, you can simplify your code a lot. There is no need for a call to MethodInfo.Invoke in your code and because of this there is no need for the delegates. You can simply call SetValue directly on the returned PropertyInfo. There is no need to use the detour of a delegate that in turn calls exactly that method anyway. Additionally, the type conversion is not necessary as SetValue requires an object anyway.
    Your code could be as simple as this:

    public class SimpleInstantiator<T> where T : new()
    {
        private T instance;
        private IDictionary<string, PropertyInfo> properties;
    
        public SimpleInstantiator()
        {
            Type type = typeof(T);
            properties = type.GetProperties()
                             .GroupBy(p => p.Name)
                             .ToDictionary(g => g.Key, g => g.ToList().First());
        }
    
        public void CreateNewInstance()
        {
            instance = new T();
        }
    
        public void SetValue(string pPropertyName, object pValue)
        {
            if (pPropertyName == null) return;
    
            PropertyInfo property;
            if (!properties.TryGetValue(pPropertyName, out property)) return;
    
            property.SetValue(instance, pValue, null);
        }
    
        public T GetInstance()
        {
            return instance;
        }
    }
    

    Performance tests show that this version takes only about 50% of the previous one.
    A tiny increase in performance is due to the fact that we avoid two unnecessary delegates in our call chain. However, the vast majority of the speed improvement lays in the fact that we removed the type conversion.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I tried to implement the solution proposed by T. Stone on my question how-do-i-pass-a-lot-of-parameters-to-views-in-django
I tried to implement this. My original post is here iphone: playing audio playlist
So, I have tried to implement the methods from Anthony/BalusC in this question: How
I tried to implement this example to write and read data from internal storage,
I tried to implement FizzBuzz in DCPU-16. I use this web emulator: http://mappum.github.com/DCPU-16/ (repository:
i have tried implement two methods recursive and dynamic method and both took 0
I tried to implement the extension method for converting ArrayList object to a List.
i tried to implement this code that move UIImageView's objects, i get a compiler
I tried to implement rss feed following this simple explanation from cake book http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html
I tried to implement this: namespace Test { void* operator new(size_t s) { return

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.