The Dink Network

Reply to Re: Overthinking it

If you don't have an account, just leave the password field blank.
Username:
Password:
Subject:
Antispam: Enter Dink Smallwood's last name (surname) below.
Formatting: :) :( ;( :P ;) :D >( : :s :O evil cat blood
Bold font Italic font hyperlink Code tags
Message:
 
 
February 14th 2019, 06:31 PM
slimeg.gif
metatarasal
Bard He/Him Netherlands
I object 
What you're really trying to do is to change the class-definition at run time. The moment you add methods to the Human class it isn't really a Human class anymore, but some derived type. In some weakly typed languages (e.g. JavaScript) you can change class definitions all the time at your leisure (so you have no idea what kind of object you are really working with), C# is a bit more strict.

The real question is what kind of problem this is trying to solve. If maximum age is a property of the Human class it should be implemented in the Human class and the Human class should have the responsibility to do the checking. If you don't have access to the Human class (because it is defined in some dependency or something) you should inherit it. If you can't change the base class and you can't inherit it you won't be able to do much because then the entire implementation is sealed. That's basically the author of the class saying 'this is what a Human is, and that's that'.

If you desperately want to do it through lambda expressions there is a way... Try this, for restricting the Age property:

public class Human
{
    private Func<int, bool> _ageRestriction;

    public string Name { get; set; }

    private int _age;
    public int Age
    {
        get { return _age; }
        set
        {
            if (_ageRestriction.Invoke(value))
                _age = value;
            else
                throw new ApplicationException("A wrong value was just passed, we shall throw an exception...");
        }
    }

    public Human(Func<int,bool> ageRestriction)
    {
        _ageRestriction = ageRestriction;
    }
}


Now you can parse a lambda-expression containing the age-restriction you want to pass to the human class like this:

Human human = new Human(ageRestriction: x => x <= 70 && x >= 0);
human.Age = 65;  //This is fine.
human.Age += 10; //This throws an exception.


Still, I think making minimum and maximum age a property of the Human class is the more semantically correct way to go about this, even though this is possibly a bit more generic.

EDIT: Wow, the code tags somehow put a semicolon after &&. I promise that isn't me doing that...