Delegate that works as a Pointer to a member function?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I need the equivalent of a pointer to a member function (as used in C++) but
in C# 2.0. I know it must be a special way of using delegates but don't know
how to make the function associated with the delegate capable of accessing
the private parts of the class.

For example, in C++ one would have:

typedef bool (CSomeClass::*TAGTEXTFUNC)( CString &rstr );

so that we could assign any method of CSomeClass to TAGTEXTFUNC, and be able
to access private parts of CSomeClass. How can one accomplish this in C#?
 
Juan,

What you have isn't able to be assigned any function from CSomeClass, it
has to have the specific signature that takes a CString and returns a bool.

In .NET you want to use a delegate. For example, to take a string and
return a boolean, you have the generic Predicate<T> delegate, which is
defined as:

// Item might not be the actual parameter name.
delegate bool Predicate<T>(T item);

If you had a class like this:

public class MyClass
{
public bool DoSomething(string item)
{
// Return some boolean value based on item.
return item.Length > 10;
}
}

You could then code this:

MyClass myClass = new MyClass();
Predicate<string> del = myClass.DoSomething;

You could then pass around del and call it like a method anywhere you
wish.
 
Juan,

To get around the protection level check:

static void Main(string[] args)
{
MyClass p = new MyClass();
Action func =
(Action)Delegate.CreateDelegate(typeof(Action), p,
"PrivateMethod");
func.Invoke();
}

~James
 
Of course, one should consider that if the method was made private, then
perhaps it shouldn't be called by outside code, or, if the coder controls
the class, then their design is wrong?
 
Nicholas said:
Of course, one should consider that if the method was made private,
then perhaps it shouldn't be called by outside code, or, if the coder
controls the class, then their design is wrong?

Not only do I agree with you, I think you could have put it a little
more strongly. :)

Access modifiers are there for a reason. If the code creating the
delegate can't call the method directly, it has no business using the
method to create a delegate. Not everything one _can_ do is an example
of something one _should_ do.

Pete
 
Back
Top