skip to Main Content

I want to create a class (eg. Person) with a member function (eg. giveCharity), but I want the contents of that method to be different for each instance of the class, imitating artificial intelligence. Is this possible? When and how would I populate the code for each instance’s method?

Here’s an example:

public class Person
{
    // data members
    private int myNumOfKids;
    private int myIncome;
    private int myCash;

    // constructor
    public Person(int kids, int income, int cash)
    {
        myNumOfKids = kids;
        myIncome = income;
        myCash = cash;
    }

    // member function in question
    public int giveCharity(Person friend)
    {
        int myCharity;
        // This is where I want to input different code for each person
        // that determines how much charity they will give their friend
        // based on their friend's info (kids, income, cash, etc...),
        // as well as their own tendency for compassion.
        myCash -= myCharity;
        return myCharity;
    }
}

Person John = new Person(0, 35000, 500);
Person Gary = new Person(3, 40000, 100);

// John gives Gary some charity
Gary.myCash += John.giveCharity(Gary);

2

Answers


  1. Why not construct the Person object by passing in a function object Charity that implements the different giveCharity(Person friend) methods.

    Then the person.giveCharity(Person friend) can simply call my_charity.giveCharity(friend).

    Login or Signup to reply.
  2. There are two primary approaches that come to mind:

    1) Give each person a delegate that defines the function:

    public Func<int> CharityFunction{get;set;}
    

    Then you just need to figure out how to set it, and ensure it’s always set before using it. To call it just say:

    int charityAmount = CharityFunction();
    

    2) Make Person an abstract class. Add an abstract function like int getCharityAmount(). Then create new sub-types that each provide a different implementation of that abstract function.

    As for which to use, that will depend more on specifics. Do you have a lot of different definitions of functions? The first option takes less effort to add a new one. Does the function ever change after an object is created? That’s not possible with the second option, only the first. Do you re-use the same functions a lot? The second option is better in that case, so that the callers aren’t constantly re-defining the same small handful of functions. The second is also a bit safer in that the function will always have a definition, and you know it won’t be changed once the object is created, etc.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search