0

Is it possible to add ToString methods to an array of delegates?? If so how?? here is the code I have written:

public delegate string Task();

        public static void Main(string[] args)
    {
        ArrayList studentArray = new ArrayList();
        Course italianCook = new ItalianCookCourse { Teacher = "Ben Hodd" };
        Course seafoodCook = new SeafoodCookCourse { Teacher = "Harry Cotter"};
        Course sewingCourse = new SewingCourse
        {
            Teacher = "Margaret Mair",
            ChargePerStudent = scFee,
            CostPerStudent = 100.00m,
        };
        Course creativeWrite = new CreativeWritCourse { Teacher = "Mary Smith };
        Course businessWrite = new BusinessWritCourse { Teacher = "Mary Smith" };
        Task[] tasks = new Task(italianCook.ToString, seafoodCook.ToString, sewingCourse.ToString);

The error message is "string Class.ToString()" - "Method name expected"

As the tostring method handle as a string, is it possible to add it to delagate??

1
  • Are those two methods you're trying to pass at the same time? That's not quite how you instantiate a single Task object or add items to a Task[] array... Commented Jul 3, 2011 at 1:15

1 Answer 1

1

Assuming you fixed up the syntax, the solution would be to remove the ()'s from the end of the ToString's. To create a delegate based on a method, you only need to give its name.

Task[] tasks = new Task[] { Class1.ToString, Class2.ToString }

Note that the above code does not actually compile. ToString() is not a static method, so you need to pass in an object reference along with the function name:

object o = new object();
Task[] tasks = new Task[] { o.ToString };
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - I did try that and got another message "(paramater) Course italianCook" "Method name expected"....??
Hi - italianCook is an instance of class Course and an object - as above it still does not work??
What does your code look like now? As BoltClock mentioned, your current syntax is incorrect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.