Click here to Skip to main content
15,895,667 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
I'd like to assign a method to a variable in C#, and use the variable to call it instead of calling the method directly. Is this possible, and if so, how would I go about it?

Thanks
Posted
Updated 20-Nov-10 12:13pm
v2

Use delegates. They are created for such things.

Click here
 
Share this answer
 
Comments
shakil0304003 21-Nov-10 1:21am    
Good Answer :)
C#
//D is the name of the delegate
public delegate void D();
class Student
{
    public void Total()
    {
        Console.Write("Enter the first number :");
        int FirstNumber = Convert.ToInt32(Console.ReadLine());
        Console.Write("Enter the second number :");
        int SecondNumber = Convert.ToInt32(Console.ReadLine());
        int Result = FirstNumber+SecondNumber;
        Console.Write("Total :"+Result);
    }
}

class Program
{
    static void Main(string[]args)
    {
        Student stu = new Student();
        D d = new D(stu.Total);
        d.Invoke();
        Console.ReadKey();
    }
}
 
Share this answer
 
v2
Comments
JOAT-MON 25-Apr-11 14:39pm    
Wrapped in code block.
Manfred Rudolf Bihy 25-Apr-11 15:19pm    
Question has a correct solution since 20th November 2010. What are you trying to do here?
Sajid Ahmed Shahsroha 30-Apr-11 0:32am    
Sir,u did a gr8 job in codeproject and i have a full respect for that..but are really serious about your reply..we can talk about later first see the posted date of the question..regards
Manfred Rudolf Bihy 2-May-11 6:48am    
But I did look at the posted date of the question and it still is 20th November 2010. Which date are you talking about?
:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900