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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T07:17:03+00:00 2026-06-12T07:17:03+00:00

The base class MasterClass holds a Dictionary containing a string key and a HookObj

  • 0

The base class MasterClass holds a Dictionary containing a string key and a HookObj value, where HookObj holds (from the derived class) the variable Type, and reference to it’s get/set methods.

Now when the base class MasterClass receives data from some source, it will cast/assign it like so:

//Data came in from an external source, see if we know what variable to assign the value to
public void receiveData(string key, string value)
{
    if (dict.ContainsKey(key))
        assignVal(dict[key], value);
    else
        throw new NotImplementedException(); //use NotImplementedException as placeholder until we make proper exception
}

//Cast the value-string to the proper type and assign it
private void assignVal(HookObj hookobj, string value)
{
    try
    {
        if (hookobj.theType == typeof(string))
            hookobj.setMethod(value);
        else if (hookobj.theType == typeof(int))
            hookobj.setMethod(Int32.Parse(value));
        else if (hookobj.theType == typeof(float))
            hookobj.setMethod(float.Parse(value));
        else
            throw new NotImplementedException();
    }
    catch (RuntimeBinderException ex) { throw new NotImplementedException("", ex); }
    catch (System.FormatException ex) { throw new NotImplementedException("", ex); }
}

With HookObj being:

internal class HookObj
{
    public Type theType { get; private set; }
    public Action<dynamic> setMethod { get; private set; }
    public Func<dynamic> getMethod { get; private set; }

    public HookObj(Type theType, Action<dynamic> setMethod, Func<dynamic> getMethod)
    {
        this.theType = theType;
        this.setMethod = setMethod;
        this.getMethod = getMethod;
    }
}

Use of the getter methods shouldn’t need explenation. So now let’s see how messy this becomes for the end user:

class Attachvariable : MasterClass
{
    public Attachvariable(int id) : base(id) { }
    public Attachvariable(int userID, string position)
        : base()
    {
        this.userID = userID;
        this.position = position;
    }

    int userID;
    string position;

    protected override void hookMethod()
    {
        newHookAndAdd(typeof(int), set_userID, get_userID, "userID").
        newHookAndAdd(typeof(string), set_position, get_position, "position");
    }

    public void set_userID(dynamic theVal)
    {
        userID = theVal;
    }
    public void set_position(dynamic theVal)
    {
        position = theVal;
    }

    public dynamic get_userID()
    {
        return userID;
    }
    public dynamic get_position()
    {
        return position;
    }
}

Where I was hoping it to be more like this:

protected override void hookMethod()
{
    newHookAndAdd(ref userID, "userID");
    //etc
}

But it’s not possible to store references for later use it seems.. is there any way to make this more user friendly? Creating two functions per variable is going to get really messy I’d guess.

  • 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-12T07:17:04+00:00Added an answer on June 12, 2026 at 7:17 am

    I did something similar to @Guffa’s answer, but instead of the objects holding “Hook” wrappers for the properties, I used lambdas to get/set the properties using their original value types:

    MasterClass:

    class MasterClass
    {
        Dictionary<string, HookObj> dict = new Dictionary<string, HookObj>();
    
        //Data came in from an external source, see if we know what variable to assign the value to
        public void receiveData(string key, string value)
        {
            if (dict.ContainsKey(key))
                assignVal(dict[key], value);
            else
                throw new NotImplementedException(); //use NotImplementedException as placeholder until we make proper exception
        }
    
        //Cast the value-string to the proper type and assign it
        private void assignVal(HookObj hookobj, string value)
        {
            try
            {
                if (hookobj.theType == typeof(string))
                    hookobj.SetValue(value);
                else if (hookobj.theType == typeof(int))
                    hookobj.SetValue(Int32.Parse(value));
                else if (hookobj.theType == typeof(float))
                    hookobj.SetValue(float.Parse(value));
                else
                    throw new NotImplementedException();
            }
            catch (RuntimeBinderException ex) { throw new NotImplementedException("", ex); }
            catch (System.FormatException ex) { throw new NotImplementedException("", ex); }
        }
    
        protected void newHookAndAdd<T>(Action<T> setter, Func<T> getter, string name)
        {
            HookObj hook = new HookObj<T>(setter, getter);
            dict.Add(name, hook);
        }
    }
    

    HookObj

    public class HookObj<T> : HookObj
    {
        public Action<T> setMethod { get; private set; }
        public Func<T> getMethod { get; private set; }
    
        public HookObj(Action<T> setMethod, Func<T> getMethod)
            : base(typeof(T))
        {
            this.setMethod = setMethod;
            this.getMethod = getMethod;
        }
    
        public override void SetValue(object value)
        {
            setMethod((T)value);
        }
    
        public override object GetValue()
        {
            return getMethod();
        }
    }
    
    
    public abstract class HookObj
    {
        public Type theType { get; private set; }
    
        public HookObj(Type theType)
        {
            this.theType = theType;
        }
    
        public abstract void SetValue(object value);
        public abstract object GetValue();
    }
    

    Then your subclasses of MasterClass:

    class Attachvariable : MasterClass
    {
        public int UserID { get; set; }
        public string Position { get; set; }
    
        public Attachvariable()
        {
            hookMethod();
        }
    
        protected void hookMethod()
        {   
            newHookAndAdd(value => UserID = value, () => UserID, "userID");
            newHookAndAdd(value => Position = value, () => Position, "position");
        }
    }
    

    You could even setup your hook registrants to provide a parser:

    class YesNoVariable : MasterClass
    {
        public bool YesNo { get; set; }
    
        public YesNoVariable()
        {
            hookMethod();
        }
    
        protected void hookMethod()
        {   
            newHookAndAdd(value => YesNo = value, () => YesNo, "yesno", (input) => input == "yes");
        }
    }
    

    I didn’t go through the motions of adding the parser as an optional parameter to the base handlers, I’ll leave that to you as it’s trivial at this stage. Essentially your assignValue would check if the HookObj has a parser assigned and if it does, to use it. Otherwise it goes through the same motions you already have.

    In fact, I would have all of the hooks use a parser and have specific IntHookObj, FloatHookObj and so on. The newHookAndAdd method would essentially be a factory. If the user provides their own parser, it would create a HookObj with that custom parser. If T is int/float/string it would instantiate a known HookObj implementation so you don’t intermix all your parsing logic with the assignment process.

    EDIT: I ended up throwing together an implementation using custom parsers and ditching the if/elseif/elseif type checks altogether:

    Hook base classes

    public abstract class HookObj<T> : HookObj
    {
        public Action<T> setMethod { get; private set; }
        public Func<T> getMethod { get; private set; }
    
    
        protected HookObj()
            : base(typeof(T))
        {
    
        }
    
        public void SetSetter(Action<T> setMethod)
        {
            this.setMethod = setMethod;
        }
    
        public void SetGetter(Func<T> getMethod)
        {
            this.getMethod = getMethod;
        }
    
        protected abstract T Parse(string value);
    
        public override void SetValue(string value)
        {
            T parsedValue = Parse(value);
            setMethod(parsedValue);
        }
    
        public override object GetValue()
        {
            return getMethod();
        }
    }
    
    
    public abstract class HookObj
    {
        public Type theType { get; private set; }
    
        public HookObj(Type theType)
        {
            this.theType = theType;
        }
    
        public abstract void SetValue(string value);
        public abstract object GetValue();
    }
    

    Standard Hook Implementations

    public class StringHook : HookObj<string>
    {
        protected override string Parse(string value)
        {
            return value;
        }
    }
    
    public class IntHook : HookObj<int>
    {
        protected override int Parse(string value)
        {
            return Int32.Parse(value);
        }
    }
    
    public class FloatHook : HookObj<float>
    {
        protected override float Parse(string value)
        {
            return float.Parse(value);
        }
    }
    

    Custom Hook Parser Handler

    public class CustomHook<T> : HookObj<T>
    {
        public Func<string, T> inputParser { get; private set; }
    
        public CustomHook(Func<string, T> parser)
        {
            if (parser == null)
                throw new ArgumentNullException("parser");
    
            this.inputParser = parser;
        }
    
        protected override T Parse(string value)
        {
            return inputParser(value);
        }
    }
    

    MasterClass:

    class MasterClass
    {
        Dictionary<string, HookObj> dict = new Dictionary<string, HookObj>();
    
        //Data came in from an external source, see if we know what variable to assign the value to
        public void receiveData(string key, string value)
        {
            if (dict.ContainsKey(key))
                assignVal(dict[key], value);
            else
                throw new NotImplementedException(); //use NotImplementedException as placeholder until we make proper exception
        }
    
        //Cast the value-string to the proper type and assign it
        private void assignVal(HookObj hookobj, string value)
        {
            hookobj.SetValue(value);
        }
    
        protected void RegisterProperty<T>(Action<T> setter, Func<T> getter, string name, Func<string, T> inputParser)
        {
            var hook = new CustomHook<T>(inputParser);
            hook.SetSetter(setter);
            hook.SetGetter(getter);
            dict.Add(name, hook);
        }
    
        protected void RegisterProperty(Action<string> setter, Func<string> getter, string name)
        {
            var hook = new StringHook();
            hook.SetSetter(setter);
            hook.SetGetter(getter);
            dict.Add(name, hook);
        }
    
        protected void RegisterProperty(Action<int> setter, Func<int> getter, string name)
        {
            var hook = new IntHook();
            hook.SetSetter(setter);
            hook.SetGetter(getter);
            dict.Add(name, hook);
        }
    
        protected void RegisterProperty(Action<float> setter, Func<float> getter, string name)
        {
            var hook = new FloatHook();
            hook.SetSetter(setter);
            hook.SetGetter(getter);
            dict.Add(name, hook);
        }
    }
    

    Now, the MasterClass could use a bit of work. Specifically, I feel that the RegisterProperty methods (which replaced newHookAndAdd) are duplicating work and you’d have to add entries for each “standard” hook type that you support. I’m sure there’s a nicer way to do it, but for now it provides your “Attachvariable” subclasses to not care about what hooks are used, they know which types are supported natively, and its typesafe. Any types not supported natively, they must supply a typesafe parser.

    Attachvariable sample:

    class Attachvariable : MasterClass
    {
        public int UserID { get; set; }
        public string Position { get; set; }
        public bool YesNo { get; set; }
        public bool ProperBoolean { get; set; }
    
        public Attachvariable()
        {
            RegisterProperties();
        }
    
        protected void RegisterProperties()
        {   
            RegisterProperty(value => UserID = value, () => UserID, "userID");
            RegisterProperty(value => Position = value, () => Position, "position");
            RegisterProperty(value => YesNo = value, () => YesNo, "yesno", (input) => input == "yes");
            RegisterProperty(value => ProperBoolean = value, () => ProperBoolean, "ProperBoolean", (input) => Boolean.Parse(input));
        }
    }
    

    The string and int properties are supported natively; they hit the RegisterProperty overloads tied to their type. However, the bool types are not supported natively so they provide their own parsing logic. The “yesno” simply checks that the string equals “yes”. The “ProperBoolean” performs the standard Boolean.Parse. Usage looks like:

    Attachvariable obj = new Attachvariable();
    
    obj.receiveData("userID", "9001");
    obj.receiveData("position", "Hello World!");
    obj.receiveData("yesno", "yes");
    obj.receiveData("ProperBoolean", "True");
    
    Console.WriteLine(obj.UserID); //9001
    Console.WriteLine(obj.Position); //"Hello World!"
    Console.WriteLine(obj.YesNo); //True
    Console.WriteLine(obj.ProperBoolean); //True
    
    obj.receiveData("yesno", "something else!");
    Console.WriteLine(obj.YesNo); //False
    
    obj.receiveData("ProperBoolean", "Invalid Boolean!"); //throws exception on `Boolean.Parse` step as intended
    

    I thought about having the “Standard” hooks inherit from the CustomHook and just pass the parse methods down, but this way you can create new standard hooks that might have more complicated parsing logic so this should make it a bit easier to read/implement. At anyrate, I whipped this off and if I were to use it in production, I’d take more time to clean/improve/test.

    A biiiiiiiig plus is this makes it very easy to unit test your individual hook type implementations. Could probably refactor the MasterClass to make it easier to unit test (albeit it’s pretty simple now), maybe move the hook creators into a separate factory/builder.

    EDIT: Heck, now just throw out the theType field on the HookObj base and replace it with an interface:

    public interface IHookObj
    {   
        void SetValue(string value);
        object GetValue();
    }
    

    You can propagate the changes throughout (HookObj<T> no longer calls a base constructor passing in typeof(T), MasterClass is now tied to an IHookObj interface). This means you can even more easily define hooks that use whatever logic they want, parsing or otherwise, and should be even easier to test.

    EDIT: Yeah, here’s a sample implementation where a third party consumer of your API can provide their own hooks that can be reused across their application. If they had Person objects used everywhere, they just define a single hook and it can get reused:

    class SomeCustomUsage : MasterClass
    {
        public Person SomeoneUnimportant { get; set; }
    
        public SomeCustomUsage()
        {
            RegisterProperty(value => SomeoneUnimportant = value, () => SomeoneUnimportant, "SomeoneUnimportant", new PersonHook());
        }
    }
    

    With their PersonHook being:

    public class PersonHook : HookObj<Person>
    {
        protected override Person Parse(string value)
        {
            string[] parts = value.Split(',');
            var person = new Person(parts[0], parts[1]);
    
            if (person.FirstName == "Bob")
                throw new Exception("You have a silly name and I don't like you.");
    
            if (String.IsNullOrWhiteSpace(person.FirstName))
                throw new Exception("No first name provided.");
    
            if (String.IsNullOrWhiteSpace(person.LastName))
                throw new Exception("No last name provided.");
    
            return person;
        }
    }
    

    Providing the HookObj<T> overload to RegisterProperty also collapsed all the overloads to something simpler with less code duplication (but still it doesn’t quite feel right yet):

    protected void RegisterProperty<T>(Action<T> setter, Func<T> getter, string name, HookObj<T> hook)
    {
        hook.SetSetter(setter);
        hook.SetGetter(getter);
        dict.Add(name, hook);
    }
    
    protected void RegisterProperty<T>(Action<T> setter, Func<T> getter, string name, Func<string, T> inputParser)
    {
        var hook = new CustomHook<T>(inputParser);
        RegisterProperty(setter, getter, name, hook);
    }
    
    protected void RegisterProperty(Action<string> setter, Func<string> getter, string name)
    {
        var hook = new StringHook();
        RegisterProperty(setter, getter, name, hook);
    }
    
    protected void RegisterProperty(Action<int> setter, Func<int> getter, string name)
    {
        var hook = new IntHook();
        RegisterProperty(setter, getter, name, hook);
    }
    
    protected void RegisterProperty(Action<float> setter, Func<float> getter, string name)
    {
        var hook = new FloatHook();
        RegisterProperty(setter, getter, name, hook);
    }
    

    Results might look like:

    SomeCustomUsage customObj = new SomeCustomUsage();
    customObj.receiveData("SomeoneUnimportant", "John,Doe");
    Console.WriteLine(customObj.SomeoneUnimportant.LastName + ", " + customObj.SomeoneUnimportant.FirstName); //Doe, John
    
    customObj.receiveData("SomeoneUnimportant", "Bob,Marley"); //exception: "You have a silly name and I don't like you."
    customObj.receiveData("SomeoneUnimportant", ",Doe"); //exception: "No first name provided."
    customObj.receiveData("SomeoneUnimportant", "John,"); //exception: "No last name provided."
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

base class class Drawer { public abstract void Draw<T>(T type); } derived class #1
A base class have readonly field of type List<SomeEnum> which the derived classes will
MasterClass is the base class, Attachvariable inherits from this. Table stores MasterClass objects. public
I have a base class like this: public class BaseResponse { public string ErrorMessage
Base class has incomplete type What exactly does this error mean and how can
Base class is Task. There are several derived classes such as PhoneCall, Fax, Email....
class Base { public: Base() {} void Foo(int x) {...} }; class Derived :
Base class MessageHandler has derived classes. They would like to pass messages to each
class Base { public: virtual void foo() {} }; class Derived: public Base {
The base class includes the field 'lbl', but its type (web.App_Code.CustomLabelControl) is not compatible

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.