Solved

Passing delegate from another class

Posted on 2007-03-19
12
362 Views
Last Modified: 2012-08-14
Hello Experts
I need help figuring out how to pass the delegate from another class. I have code that looks something like this:


Class1
{
public delegate void test(string)

Method1()
{
test delTest=new test(Method2)
class2.method(delTest)
}

BOOL Method 2(string)
{
blah...
}

}

Class2 // Independent stand alone class
{
  Method(NOT SURE HOW TO receive delegate from Class1 here)
  {
  If (PASSED DELEGATE==true)
     do something
  }
}

Also, if the method my delegate is pointing to is a BOOL type... Do I need to make my delegate a BOOL type instead of Void as well ? I would appreciate any comments/suggestions as I'm new and learning.
Thank you.
0
Comment
Question by:compulaw
  • 4
  • 4
  • 4
12 Comments
 
LVL 29

Assisted Solution

by:Gautham Janardhan
Gautham Janardhan earned 200 total points
ID: 18754286
Method(delegate Test)
  {
  If (Test("value") ==true)
     do something
  }
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 18754306
     public class Class2
      {
            public delegate bool FDelegate (string Test);
            public Class2()
            {
                  FDelegate Fnew = new FDelegate(Target);
                  Class3.CallMe(Fnew,this);
            }
            bool Target(string Test)
            {
                  return true;
                  
            }
            
      }
      public class Class3
      {
            public static void CallMe(Delegate FTemp,Class2 FObj)
            {
                  if( (bool)FTemp.Method.Invoke(FObj,new string[]{""}))
                  {
                        Console.WriteLine(true);
                  }
            }                                    
      }
0
 

Author Comment

by:compulaw
ID: 18754350
Class2 ( well Class3 in gauthammpj's example ) is a separate class and it doesn't see "Delegate FTemp" from the first class. Do I need to reinitialize the delegate in the second class ?
Could you explain this line " public static void CallMe(Delegate FTemp,Class2 FObj)" a little bit more please ?
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 18754364
CallMe(Delegate FTemp,Class2 FObj)

Delegate is a struct in the .net Frame work. this will be the base object of ur deleagate .. u need to pass the object of class 2 to class 3 because then only u can invoke the method containied in the delegate that u are passing thru.

<it doesn't see "Delegate FTemp"> ?
what d'u mena by this

and

<reinitialize the delegate in the second class >
No

0
 
LVL 12

Expert Comment

by:andrewjb
ID: 18754874
Try this:

  public delegate bool MyDelegate( int a , string b );

  public class ClassA
  {
    public void Do()
    {
      ClassB b = new ClassB();

      b.ProcessDelegate( new MyDelegate( IWillBeCalled ) );

      // Alternative, shorthand way to call
      b.ProcessDelegate( IWillBeCalled );
    }

    private bool IWillBeCalled( int x , string toTest )
    {
      return ( x == 10 ) && ( toTest.Length > 2 );
    }
  }

  public class ClassB
  {
    public void ProcessDelegate( MyDelegate d )
    {
      if ( d( 10 , "Hello there" ) )
      {
        Console.WriteLine( "It's true!" );
      }
    }
  }



and, gauthampi, a Delegate is a class, not a struct.
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 18754931
sorry :-)
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:compulaw
ID: 18757232
Thank you for another example but the same problem remains.
The error message comes up in Class B " The type or namespace name 'MyDelegate' ( or 'Delegate' in gauthampj's example ) could not be found ( you are missing a using directive or an assembly reference?)

0
 
LVL 12

Expert Comment

by:andrewjb
ID: 18757303
Not if you've copied exactly what I posted, and put both ClassA and ClassB in the same namespace it doesn't :-)
0
 

Author Comment

by:compulaw
ID: 18757871
Very confused :-/
Here guys, i'll paste the actual code.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;

namespace importer
{
    class Program
    {
        public delegate bool asciiRecordSender(string asciiRecord);
       
        static void Main(string[] args)
        {
           
            string asciiRecord;

            readconifg.readconfig();

            recordprocessor asciiProcessor = new recordprocessor(readconifg.FilePath);
            asciiRecord=asciiProcessor.recordProcessor(); // gets the asciiRecord for processing


            asciiRecordSender recordSender = new asciiRecordSender(ProcessAsciiRecord); //delegate

            recordprocessor asciiReader = new recordprocessor(readconifg.FilePath);
            asciiReader.Execute(recordSender,asciiRecord); //delegate


     
        }

        static bool ProcessAsciiRecord(string asciiRecord)
        {

           
            List<string> tempList= new List<string>();
            string[] dummy = new string[1] { "" };
           

            tempList = new List<string>();
            tempList.AddRange(splitter.splitting(asciiRecord, "\"", ","));
            if (tempList.Count != 9)
            {
                Console.WriteLine("ERROR,ERROR,ERROR,ERROR,ERROR!");
               
            }

            Console.WriteLine("Line Added");
            for (int i = 0; i < tempList.Count; i++)
            {
                Console.WriteLine(tempList[i]);
            }

           
        }//end of bool Processing AsciiRecord method


SECOND CLASS:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;

namespace importer
{
    class recordprocessor
    {
        StreamReader m_reader = null;
        int m_count = 0;
        string error;


        public recordprocessor(string dbFilePath)
        {
                m_reader = new StreamReader(dbFilePath);
        }//end of recordprocessor constructor


        public void Execute( asciiRecordSender recordSender,string asciiRecord)  /* THIS IS WHERE THE ERROR COMES UP saying that asciiRecordSender could not be found) */
        {
            if (recordSender(asciiRecord) == true)
            {
                while ((record = m_reader.ReadLine()) != null)
                {

                    // Do something with the ascii record.

                }//end of while loop
            }// end of if statement
        }//end of void Execute


        public string recordProcessor()
        {
            string record;
            while ((record=m_reader.ReadLine()) != null)
            {
                return record;
               
            }//end of while, adding to the ArrayList
       }//end of recordProcessor method



    }//end of class
}
Whats wrong with this code and passing the delegate ?
0
 
LVL 12

Expert Comment

by:andrewjb
ID: 18757913
Move your delegate definition outside of the 'Program' class. Just put it directly into the namespace.
0
 
LVL 12

Accepted Solution

by:
andrewjb earned 300 total points
ID: 18757919
i.e...

namespace importer
{
    class Program
    {
        public delegate bool asciiRecordSender(string asciiRecord);
        ....      

becomes

namespace importer
{
    public delegate bool asciiRecordSender(string asciiRecord);

    class Program
    {
       ...
0
 

Author Comment

by:compulaw
ID: 18758226
Ahhhhhh... Thank you :)
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now