Can I create a delegate that would behave like this?
// here I have delegate
delegate ... MyDel ...
MyDel del = SomeMethod; // or even lambda?
int number = del<int>(...);
As an idea, it's probably a duplicate question, but I'm pointing at this ->
int n = del<int>(...);
So, can a delegate be generic function? If not (and I'm pretty sure it can't), why is it implemented this way? In what cases could it be a problem?
No, a delegate instance cannot point to an open generic method.
I can only speculate why this is so, but I'd assume that the cost of this language feature does not outweigh its benefits, given that it'll probably not be used often. See Eric Lippert's answer here on how features get into C#.
Delegates do not allow such functionality; for that you need to define an interface; some examples:
interface IActOnAnything
{
void Invoke<T>(T it)
}
interface IActOnAnything<TP1>
{
void Invoke<T>(T it, TP1 p1)
}
interface IActOnAnythingByRef
{
void Invoke<T>(ref T it)
}
Unfortunately, there's no language support to facilitate implementation of such interfaces. If a class will only need to define one function which implements the interface, one could simply declare the implementation at the class level. Otherwise, one should probably declare for each implementation a nested private class which implements the interface and holds an object of its parent type.
Yes, it's possible:
public delegate int Test<T>(T input) where T : struct;
public static event Test<int> TestEvent;
static void Main(string[] args)
{
var n = TestEvent(5);
}
Yes it is possible, like Func, Action, and also you can make your own:
delegate TOutput MyDelegate<TInput,TOutput>(TInput input);
MyDelegate<string, int> myDelegate = input=>input.Length;
Also you can do this:
int n = new MyDelegate<string, int>(input => input.Length)("MY STRING"); //n=9
Related
Suppose that my namespace has 2 delegates:
public delegate void D1(string s);
public delegate void D2(string s);
They are implemented in a static class StClass like this:
public static D1 myD1 { get; set; }
public static D2 myD2 { get; set; }
In each instance of a separate non-static class MyClass I would like to include a delegate that points to one of the 2 static delegates as determined by the constructor. So I would have:
public class MyClass
{
public delegate void D(string s);
public D myD { get; set; }
public MyClass()
{
if()
{
myD = StClass.myD1 //this assignment won't work
}
else
{
myD = StClass.myD2
}
}
I get that I cannot directly link myD to myD1 or myD2 the way it's shown above because from the compiler's standpoint they are instances of different delegate types, but I figure since they all share the same signature there should be a simple way to achieve this. What am I missing?
As per comments, it would probably be better to avoid declaring multiple delegate types with the same signature like this.
However, if you absolutely have to, you can convert them like this:
myD = new D(StClass.myD1);
Note that this uses the value of StClass.myD1 at the time of assignment. If you want to dynamically observe any changes in StClass.myD1, you could use a lambda expression instead:
myD = s => StClass.myD1(s);
This will evaluate the StClass.myD1 property on each invocation.
You start by saying "Suppose that my namespace has 2 delegates:"
public delegate void D1(string s);
public delegate void D2(string s);
But, that's not what you are showing. You are showing the declaration of two, different Delegate Types. You still haven't declared a delegate yet.
Then, within your class, you declare a third delegate type, and an instance of that type:
public delegate void D(string s);
public D myD { get; set; }
Now you start trying to assign delegates of one type to another. That's never going to work; two delegate types, even if their definition completely agrees, remain distinct types. Somewhere, #EricLippert has a blog entry that explains this in detail (but, after a quick search, I can't find it). The pair of types that show this that most C# programmers are familiar with (and curse at) are:
delegate bool Predicate<in T>(T obj);
and
Func<T, bool>
The latter is used for the IEnumerable<T>.Where() extension method, while the former is used in methods like List<T>.FindAll(). Grrrr
The solution, as others have pointed out, is to use a single delegate type. Both the generic Action and Func delegates have been around for nearly forever now. I rarely define delegate types anymore, instead relying on those two types.
I'm trying to restrict the return type of a generic delegate without specifying the parameter signature, and I don't know how to do this, or if it is even possible.
How can I do this or is it impossible?
My research has come up dry. Some pseudo-C# code would probably help steer you toward what I'm trying to do:
public class SomeClass< T, U > where T : Delegate // returning U
{
private someDelegate;
public SomeClass( T someDelegate )
{
this.someDelegate = someDelegate;
}
public U Run()
{
return someDelegate.DynamicInvoke();
}
}
... Elsewhere
public delegate string aDelegate();
public static string SayHi()
{
return "Hello!";
}
aDelegate greeter = SayHi;
var something = new SomeClass< aDelegate, string>( greeter );
Console.WriteLine( something.Run() ); // Should write "Hello" to the console.
I know this is a rather contrived pseudo example. I aim for a more involved usage, of course. I'm trying to write a console menu class that would associate a list of given menu options with actions that would fire depending on what option the user chooses. Right now, it just returns the string the user chose from the menu. What I'd like be able to do is return what--if anything--the associated method returns. This could perhaps be returned with the user chosen option string in a tuple... But, I figured this mini-example just cut straight to the technical hurdle I'm experiencing.
Thanks!
.NET already defines a generic delegate that returns the generic argument as it's result, Func<T>. You don't even need to define it.
public class SomeClass<U>
{
private Func<U>;
public SomeClass(Func<U> someDelegate)
{
this.someDelegate = someDelegate;
}
public U Run()
{
return someDelegate();
}
}
There's no real useful reason to allow a user of the type to provide any arbitrary delegate of the same signature. Really I'd advise you to avoid using any delegates in your code other than Func and Action (with various different numbers of generic arguments) whenever possible, as it's just creating a hassle to do so. I would consider it a reasonable restriction on any caller that has a delegate of a different type but the same signature to simply convert it to a Func<T> anyway, it's not like it's even a difficult conversion for them.
If you don't want to use Func<T> (as Servy suggests), e.g. if you have a custom delegate of your own that you want to be passed with type-safety, then perhaps you can make your custom delegate generic with respect to its return type. Then you can do it this way:
public delegate T MyDelegate<T>();
public class Foo<T>
{
private readonly MyDelegate<T> _delegate;
public Foo(MyDelegate<T> handler)
{
_delegate = handler;
}
public T Bar()
{
return _delegate();
}
}
I would like to understand if/when to use delegates and interfaces in my code. The structure is pretty simple. The main class initialize a windows form:
class MainClass
{
public static void Main()
{
InputForm InputForm1 = new InputForm();
InputForm1.ShowDialog(); // show interface to prompt user
}
}
And the class for the form has a button and few more methods:
public partial class InputForm : Form
{
public InputForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// do some calculation and then create a dictionary of items
for (int n = 1; n <= dict.Count; n++) // loop through items
{
dict[n].calculatedLength = theLength.calcLength(arg1, arg2, dict[n].speed);
}
}
}
When the button is clicked, the program does some calculation (calling methods in the same class InputForm) and save results into a dictionary (dict). Each element is an animal and I have some properties that I store in the dictionary (e.g. under the key "Dog" I have an average weight of dogs, an average speed, etc.).
Using the speed and two default arguments (arg1 that is the number of hours and arg2 that is the number of minutes) I have to call the method of the class LengthClass in order to get the estimated length that is covered by the specific animal in arg1 hours and arg2 minutes.
The LengthClass is like this:
class LengthClass
{
static double calcLength(double arg1, double arg2, double speed)
{
// do some calculation
return x;
}
}
Now the question: is there space in this example to use delegates and interfaces? Can you please show me how to best do it and what are the advantages/disadvantages in doing so instead of calling the calcLength method directly as I'm doing?
EDITED: I included the Microsoft guideline
Microsoft Guideline
Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method. Given these similarities, when should a class designer use a delegate and when should it use an interface?
Use a delegate in the following circumstances:
An eventing design pattern is used.
It is desirable to encapsulate a static method.
The caller has no need to access other properties, methods, or
interfaces on the object implementing the method.
Easy composition is desired.
A class may need more than one implementation of the method.
Use an interface in the following circumstances:
There is a group of related methods that may be called.
A class only needs one implementation of the method.
The class using the interface will want to cast that interface to
other interface or class types.
The method being implemented is linked to the type or identity of the
class: for example, comparison methods.
The original answer (What I think)
Interfaces and delegates were made to make things easier when two classes have the same proprieties/behaviours.
I think that if you had something like that
private void Button(object sender, EventArgs e)
{
List<IAnimal> animals = Farm.GetAnimals();
foreach(IAnimal animal in animals)
{
dict[animal.name] = LeghtClass.CalculateLenght(animal);
//dict[animal.name] = animal.CalculateOwnLenght(); //using a method in the interface
}
}
You wouldn't have to worry about passing the method its parameters (wichh would help you when refactoring).
interface IAnimal
{
double Hours;
double Minutes;
double GrowSpeed;
//void CalculateOwnLenght();
}
And your lenght class would calculate it like that:
class LengthClass
{
static double calcLength(IAnimal animal)
{
return (animal.Hours + animal.Minutes / 60) * animal.GrowSpeed;
}
}
I can't think how delegates would help you unless if you do something like that:
foreach(var animal in animals)
{
delegate = animal.CalculateOwnLeght;
dict[animal.name] = delegate();
}
Ok, I have shown some code without saying anything.
I think interfaces are useful if you use them in more than one place, otherwise it can be messy - you just repeat youself more when using interfaces.
I personally don't think your way is wrong but I've read people saying that static is bad practise without proving why in a way I could understand, the one thing I remember is that it gets confusing easily and uses more resources.
I'd use delegates when I have to point to some method but I don't know the object of untill the code is running (they don't have mush use for this case, I think).
delegate void Cry();
...
cat = new Cat(); dog = new Dog();
...
foreach(var animal in animals)
{
if (animal is Cat)
{
Cry = cat.meow;
}
else if (animal is Dog)
{
Cry = dog.bark;
}
else {...}
if (animal.isInPain)
{
Cry();
}
}
Since i am new to c#, would like to know about Interfaces and Delegates in c#, the difference between them and scenarios both these to be used. Please don't provide any links, i would like an explanation in simple words.
An interface is a contract - it defines methods and properties that any implementing class has to have and as such any consumer of the interface will know they exist and can use them.
A delegate is a call back site - it defines a method signature that can invoke any method that has the same signature.
See delegates and interfaces on the C# programming guide.
An example of an interface is the IEnumerable interface. It only has one member defined - GetEnumerator. Any object that implements this interface will have this method and any code using such an object can call this method.
An example of a delegate is the Predicate<T> delegate. It is a generic delegate that is defines as following:
public delegate bool Predicate<in T>(T obj);
This means that it takes in any type T and returns a bool. Any method that takes a single type parameter and returns a bool is a match for this delegate and can be used with it.
Since delegates are also objects, they can be passed in to functions. So, any function that has a Predicate<T> delegate can pass in any mathod that matches it. Many of the Linq operators have delegates as parameters. See examples here.
A quote from C# in Nutshell.
A problem that can be solved with a delegate can also be solved with an
interface. For instance, the following explains how to solve our filter problem using
an ITransformer interface:
public interface ITransformer
{
int Transform (int x);
}
public class Util
{
public static void TransformAll (int[] values, ITransformer t)
{
for (int i = 0; i < values.Length; i++)
values[i] = t.Transform (values[i]);
}
}
class Squarer : ITransformer
{
public int Transform (int x) { return x * x; }
}
...
static void Main()
{
int[] values = { 1, 2, 3 };
Util.TransformAll (values, new Squarer());
foreach (int i in values)
Console.WriteLine (i);
}
A delegate design may be a better choice than an interface design if one or more of
these conditions are true:
The interface defines only a single
method.
Multicast capability is needed.
The subscriber needs to implement the
interface multiple times.
In the ITransformer example, we don’t need to multicast. However, the interface
defines only a single method. Furthermore, our subscriber may need to implement
ITransformer multiple times, to support different transforms, such as square or cube.
With interfaces, we’re forced into writing a separate type per transform, since Test
can implement ITransformer only once. This is quite cumbersome:
class Squarer : ITransformer
{
public int Transform (int x) { return x * x; }
}
class Cuber : ITransformer
{
public int Transform (int x) {return x * x * x; }
}
...
static void Main()
{
int[] values = { 1, 2, 3 };
Util.TransformAll (values, new Cuber());
foreach (int i in values)
Console.WriteLine (i);
}
And here is the code with delegate
public delegate int Transformer (int x);
class Util
{
public static void Transform (int[] values, Transformer t)
{
for (int i = 0; i < values.Length; i++)
values[i] = t (values[i]);
}
}
class Test
{
static void Main()
{
int[] values = { 1, 2, 3 };
Util.Transform (values, Square); // Dynamically hook in Square
foreach (int i in values)
Console.Write (i + " "); // 1 4 9
}
static int Square (int x) { return x * x; }
}
An interface can be thought of as a functional definition (or contract). In the real world, many objects have well known interfaces that make them largely (but not completely) interchangable.
For example, take a car. Once you learn how to drive a car, you learn the "Car Driving Interface". You know there will be an Accelerate() function, and a Stop() function, and typically a ShiftGears() function (even if it's just taking it out of park and putting into drive). There is also a Steer() function, and a SignalTurn() function.
There is no guarantee that any given implementation will do something the same way. For instance, a Toyota may have a "Stop()" method in it's CarDriving interface that actually calls Accelerate().
The car may support additional intefaces, such as the SeatBelt inteface, or the Radio interface. While each implementation of these objects may differ, there is always a core set of functionality that is common among all types of these objects. This allows them to be used largely interchangably without having to relearn a different interface.
Interfaces in C# are similar. Different object implementations may contain the same interface implementation, and what they do may be different, but you can treat one object that implements a specific interface the same way you treat another object that implements the same interface.
If you understand what inheritence is, then another way to think of interfaces is that they are the same as a class, but they have no implementation. So when a class inherits from another class, it inherits both that classes "inteface" and it's "implementation". If a class inherts only an interface, then it lacks an implementation and the new class must create that implementation itself.
A delegate, is completely different. A delegate is (among other things) a function pointer that is object aware. A function pointer is a variable, similar to other variables but it's type is "delegate" rather than "int" or "string". And, instead of holding data, it holds a pointer to a method (along with some state information) so that you can call different functions dynamically at run time.
In the following code, the call to "foo" is fixed. You cannot, at runtime, decide you want to call "bar" instead:
DoSometing()
{
foo();
}
If, instead you did something like the following, you can then pass different methods as arguments to your method and have it call them dynically:
DoSomething(MyFunction func)
{
MyFunction myfunc = func;
myfunc();
}
Delegats can do more than that, but that's a basic way to think of them.
OK, I can talk to you in English. You are human. I can talk to any human in English; I don't need to know all humans on earth to speak to them in English; all I care about is that they speak English.
OK, so a human is an object. English is the interface.
A lot of Humans implement the interface IEnglish!
Now apply that in a classical engineering sense. I have a car and a car battery. The car doesn't care about what type of battery, where it was made, or what shape it is.
The battery doesn't care about the car. They are functionally abstract from each other.
The battery gives power and implements the interface IBattery. The car will ONLY accept objects which implement IBattery (i.e. physical objects which are car batteries!!)
Semantically, interfaces and delegates are largely equivalent. An interface defines what an object does (methods and properties)... and a delegate defines what a particular method does. Delegates state the parameters of a function or method.... they are type safe function pointers. I'll need to have more of a think to come up with a real life example for this.
An interface is a collection of methods bound to a single object. (Side note: Objects may expose multiple interfaces, thus enabling them to exhibit multiple "personalities").
A delegate is an abstraction of a single method call. Calling a delegate has the effect of calling some other piece of code, about which the caller knows nothing.
A somewhat oversimplified view of things that nonetheless gives the flavour is to think of a delegate as a special case of an interface with exactly one method.
A delegate is a function pointer. So it points to a function which meets the criteria (parameters and return type).
This begs the question (for me, anyway), what function will the delegate point to if there is more than one method with exactly the same return type and parameter types? Is the function which appears first in the class?
Thanks
The exact method is specified when you create the Delegate.
public delegate void MyDelegate();
private void Delegate_Handler() { }
void Init() {
MyDelegate x = new MyDelegate(this.Delegate_Handler);
}
As Henk says, the method is specified when you create the delegate. Now, it's possible for more than one method to meet the requirements, for two reasons:
Delegates are variant, e.g. you can use a method with an Object parameter to create an Action<string>
You can overload methods by making them generic, e.g.
static void Foo() {}
static void Foo<T>(){}
static void Foo<T1, T2>(){}
The rules get quite complicated, but they're laid down in section 6.6 of the C# 3.0 spec. Note that inheritance makes things tricky too.
So it points to a function which meets the criteria (parameters and return type).
Nope.
To add some background to Henk's Answer:
Just like int x is an variable which can contain integers, A delegate is a variable which can contain functions.
It points to whatever function you tell it to point to.
EG:
// declare the type of the function that we want to point to
public delegate void CallbackHandler(string); //
...
// declare the actual function
public void ActualCallbackFunction(string s){ ... }
...
// create the 'pointer' and assign it
CallbackHandler functionPointer = ActualCallbackFunction;
// the functionPointer variable is now pointing to ActualCallbackFunction