Solved

Passing delegate from another class

Posted on 2007-03-19
12
365 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
detecting  the added row index in a datagridview 3 62
Is setting this variable making a duplicate in memory 4 31
Allow space in this pattern 2 49
Class object 2 28
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

863 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

23 Experts available now in Live!

Get 1:1 Help Now