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 9089399
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T22:08:24+00:00 2026-06-16T22:08:24+00:00

I have a factory method that returns the correct sub class depending on three

  • 0

I have a factory method that returns the correct sub class depending on three enum values.
One way to do is, would be to use switches in switches in switches. Obviously, I don’t like that option very much.

I thought that another option would be to use attributes in C#. Every sub class would have an attribute with that 3 enum values and in the factory I would only have to get the class that has the same enum values corresponding to the enum values i have in the factory.

However, I am quite new to attributes and I did not find any suitable solution in the web. If anyone, could just give me some hints or some lines of code, I really would appreciate that!

  • 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-16T22:08:25+00:00Added an answer on June 16, 2026 at 10:08 pm

    First of all, declare your attribute and add it to your classes.

    enum MyEnum
    {
        Undefined,
        Set,
        Reset
    }
    
    class MyEnumAttribute : Attribute
    {
        public MyEnumAttribute(MyEnum value)
        {
            Value = value;
        }
    
        public MyEnum Value { get; private set; }
    }
    
    [MyEnum(MyEnum.Reset)]
    class ResetClass
    {
    }
    
    [MyEnum(MyEnum.Set)]
    class SetClass
    {
    }
    
    [MyEnum(MyEnum.Undefined)]
    class UndefinedClass
    {
    }
    

    Then, you can use this code to create a dictionary with your enums and types, and dynamically create a type.

    //Populate a dictionary with Reflection
    var dictionary = Assembly.GetExecutingAssembly().GetTypes().
        Select(t => new {t, Attribute = t.GetCustomAttribute(typeof (MyEnumAttribute))}).
        Where(e => e.Attribute != null).
        ToDictionary(e => (e.Attribute as MyEnumAttribute).Value, e => e.t);
    //Assume that you dynamically want an instance of ResetClass
    var wanted = MyEnum.Reset;
    var instance = Activator.CreateInstance(dictionary[wanted]);
    //The biggest downside is that instance will be of type object.
    //My solution in this case was making each of those classes implement
    //an interface or derive from a base class, so that their signatures
    //would remain the same, but their behaviors would differ.
    

    As you can probably notice, calling Activator.CreateInstance is not performant. Therefore, if you want to improve the performance a little bit, you can change the dictionary to Dictionary<MyEnum,Func<object>> and instead of adding types as values you would add functions wrapping the constructor of each of your classes and returning them as objects.

    EDIT: I’m adding a ConstructorFactory class, adapted from this page.

    static class ConstructorFactory
    {
        static ObjectActivator<T> GetActivator<T>(ConstructorInfo ctor)
        {
            var paramsInfo = ctor.GetParameters();
            var param = Expression.Parameter(typeof(object[]), "args");
            var argsExp = new Expression[paramsInfo.Length];
            for (var i = 0; i < paramsInfo.Length; i++)
            {
                Expression index = Expression.Constant(i);
                var paramType = paramsInfo[i].ParameterType;
                Expression paramAccessorExp = Expression.ArrayIndex(param, index);
                Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType);
                argsExp[i] = paramCastExp;
            }
            var newExp = Expression.New(ctor, argsExp);
            var lambda = Expression.Lambda(typeof(ObjectActivator<T>), newExp, param);
            var compiled = (ObjectActivator<T>)lambda.Compile();
            return compiled;
        }
    
        public static Func<T> Create<T>(Type destType)
        {
            var ctor = destType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).First();
            Func<ConstructorInfo, object> activatorMethod = GetActivator<Type>;
            var method = typeof(ConstructorFactory).GetMethod(activatorMethod.Method.Name, BindingFlags.Static | BindingFlags.NonPublic);
            var generic = method.MakeGenericMethod(destType);
            dynamic activator = generic.Invoke(null, new object[] { ctor });
            return () => activator();
        }
    
        delegate T ObjectActivator<out T>(params object[] args);
    }
    

    You can use it as an alternative to Activator.CreateInstance, it provides greater performance if the result is cached.

    var dictionary = Assembly.GetExecutingAssembly().GetTypes().
        Select(t => new { t, Attribute = t.GetCustomAttribute(typeof(MyEnumAttribute)) }).
        Where(e => e.Attribute != null).
        ToDictionary(e => (e.Attribute as MyEnumAttribute).Value, 
                     e => ConstructorFactory.Create<object>(e.t));
    var wanted = MyEnum.Reset;
    var instance = dictionary[wanted]();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a script with a factory method that I would like to return
I have a factory class, DocumentLoaderFactory , which simply returns an instance that implements
I have a class EnumConverter<T extends Enum<?>> that converts strings to the correct enum
I basically have a class that has a factory method that takes in a
I have a method on one of my objects that returns a new instance
I have a factory method that generates django form classes like so: def get_indicator_form(indicator,
I have a generic object factory FactoryBase<T> with a factory method: public abstract class
I have a factory that returns a smart pointer. Regardless of what smart pointer
So I have an unmanaged DLL that exports only a C style factory method
I have a method that returns a task like: public static Task<int> SendAsync(this Socket

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.