Anonymous methods not omitting parameters anymore? - c#

I have been workig on a report on delegates for some time now in addition to working with them for over a year.
Looking up some info on the differences between anonymous methods used in C# 2.0 and lambda expressions in C# i read something about a functionality that 2.0 anonymous methods provide which lambda's dont: they can omit the parameter list.
After doing some research on this i try testing this out on my personal IDE which is running the latest version of C#, finding out that when i try to assign an anonymous method without any parameters to my Delegate type using them i get an error:
Delegate Test.MyHelloDelegate does not take 0 arguments
class TestClass
{
public delegate void MyHelloDelegate (string s);
MyHelloDelegate Hello = delegate () { Console.WriteLine("Hello from delegate"); };
private void CallHello ()
{
Hello("dummy");
}
}
My own assumption would be that it got patched out since people will only use lambda's anyway but i do need some evidence for that since i will be putting it in my report. Would love to know if someone has any idea what is going on with this.

Yes, cause your attached anonymous method doesn't takes an input parameter. Change it to
public delegate void MyHelloDelegate (string s);
MyHelloDelegate Hello = delegate(string s) { Console.WriteLine("Hello from delegate " + s); };
If you don't want pass any parameter then consider using the syntax below
MyHelloDelegate Hello = delegate { Console.WriteLine("Hello from delegate "); };

Related

Action <T> usage as parameter

I just started with .net core and found Action<T> used everywhere. I have provide sample code from Swagger code block below. My question is what is the use of using Action<T> here? I need to pass config data. How does Swagger extract that configuration data?
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "My API",
Description = "My First ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact() { Name = "Talking Dotnet", Email = "x#x.com", Url = "www.x.com" }
});
});5
It's a lambda function which does not return anything. You could supply a void returning method there.
Here it's just used so that you can supply a function that does something with T. It means the library can create a default options object and give you a way of modifying it.
The method would be doing something like
public void AddFoo(Action<FooOptions> configure) {
// Create a default configuration object
var options = new FooOptions();
// Let the action modify it
configure(options);
// Do something with the now configured options
}
When you see a variable or a parameter of type Action, that means it is a reference to a method call. For example:
//Declare a method with no parameters
void ShowMessage()
{
Console.WriteLine("Hello world");
}
//Store a reference to that method in x
Action x = ShowMessage;
//Call that method
x(); //Displays "hello world"
Using a lambda expression, you can also define the method body inline, like this:
//Declare a lambda expression and store a reference to it in x
Action x = () => Console.WriteLine("Hello world");
//Call that method
x(); //Displays "hello world"
Now what if you need to store a reference to a method that takes parameters? Well, Action<T> is generic, meaning that various kinds of Action<T> can take parameters of different types. For example, an Action<string> can accept a string parameter.
void ShowMessage(string message)
{
Console.WriteLine(message);
}
Action<string> x = ShowMessage;
x("Hello world"); //Displays "Hello world"
Or as a Lambda:
Action<string> x = message => Console.WriteLine(message);
x("Hello world"); //Displays "Hello world"
When a method accepts an action as an argument, is is typically going to be used as a callback. For example, LINQ's Where method accepts a delegate that is executed for each item in a list and uses its output to determine whether the item should be included in the results.
With AddSwaggerGen you are providing a reference to a method that Swashbuckle will call at some point. I believe the method in this case is supposed to generate Swagger (typically using SwaggerDoc).

c# / c++ member function pointers

Is it possible to store member functions in C++ the way delegates are used in C#?
How do Delegates accomplish the object-instance, memberFuncPtr pairs and calls without knowing anything about the instance class?
(note: this questions arose while I was trying to understand events/delegates in publisher/subscriber code design)
I read that:
C++ requires knowledge of a class type such as ClassType::*FuncPtr
C# delegates allow someDelegate += classInstance.memberFunc
There is type called std::function,but if you are using older version of C++ (older than C++11) you will need to use raw function pointers.Check function pointers in C,they are the same for C++.
Not getting exactly what you are asking.
But you can store member functions in form of function pointers in c++.
void yourFunc(int x);
int main()
{
void (*funcPtr)(int)=&yourFunc;
(*funcPtr)(10);
}
Or
A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
/* The above line is equivalent of following two
void (*fun_ptr)(int);
fun_ptr = &fun;
*/
// Invoking fun() using fun_ptr
(*fun_ptr)(10);
return 0;
}

Creating a Func<object[], object> Delegate from MethodInfo

After much research and searching on SO; I've failed to find an answer that encompasses my specific situation. I wish to add modding capabilities to my project; currently I use a 3rd-party C# API which can convert scripts written in a particular interpreted language (specifically the functions in these scripts) into C# delegates.
Is there a way to wrap all of the delegates I get from the 3rd party API, into the a generic Func Delegate? My thoughts (in code) follow...
//The goal signature for all 'imported' delegates
public delegate object GenericSignature(object[] args);
//A fictional example...
public class Program
{
public static void Main()
{
GenericSignature desiredFunc = GenerateFromArbitraryMethod(
Program.FictionalArbitraryMethod);
object retVal = desiredFunc(1, new object(), "If only this worked");
}
public static FictionalArbitraryMethod(int num, object stuff, string name)
{
//code from mod author would be here
}
}
//Attempt #1
//If my understanding about Delegate.CreateDelegate() is correct,
//this will not work...
public GenericSignature GenerateFromArbitraryMethod(Delegate d) {
MethodInfo mInfo = d.Method;
return (GenericSignature) Delegate.CreateDelegate(typeof(GenericSignature), mInfo);
}
//Attempt #2
//seems a bit... better?; I can do some validation, but how do I actually call the
//function represented by MethodInfo since it's signature is arbitrary?
public GenericSignature GenerateFromArbitraryMethod(Delegate d) {
MethodInfo mInfo = d.Method;
return delegate(object[] args) {
ParameterInfo[] pInfo = mInfo.GetParameters();
if(args.length != pInfo.length) {
throw new Exception("Argument count does not match");
}
for(int i = 0; i < args.length; i++) {
if(pInfo[i].ParameterType != args[i].GetType()) {
throw new Exception("Incorrect Type for argument");
}
}
//At a loss of how to do the following; fake psuedo-code follows
/*
Foreach(object currentArg in arg) {
d.AppendArgAndCast(currentArg);
}
return d.Call();
or...
return d(EachOrUnpackAndCast(args));
*/
};
}
Apologies if there are any errors in the syntax; I'm mainly trying to get across the concept of what I'm trying to achieve. Some additional notes:
Based on info from here; Unity supports .NET 3.5 features; so the solution I would use can leverage up to .NET 3.5.
It is ok if any suggested solution is 'slow/heavy' due to heavy use of reflection; as long as I can generate a delegate, which I can cache and just call many, many times (to amortize the initial delegate creation cost)
Delegate.DynamicInvoke() does not meet my project's performance requirements. My understanding is reflection APIs are used per DynamicInvoke() call. Using reflection one time to create the faster delegate is preferable.
You need to compile your own bytecode to cast each argument from object to the correct type.
If you can upgrade from .Net 2, Expression makes this very easy.
If not, you'll need to use ILGenerator, or a wrapper such as Sigil.

Performance differences between overloading or optional parameters?

I wonder if I should be using optional parameters in C#. Until now I was always overloading methods. But optional parameters are nice too, cleaner and less code. And I use them in other languages so I'm also used to them in some way. Is there anything that speaks against using them ? Performance is the first key point for me. Would it drop ?
Example code:
class Program
{
// overloading
private static void test1(string text1)
{
Console.WriteLine(text1 + " " + "world");
}
private static void test1(string text1, string text2)
{
Console.WriteLine(text1 + " " + text2);
}
// optional parameters
private static void test2(string text1, string text2 = "world")
{
Console.WriteLine(text1 + " " + text2);
}
static void Main(string[] args)
{
test1("hello");
test1("hello", "guest");
test2("hello"); // transforms to test2("hello", "world"); ?
test2("hello", "guest");
Console.ReadKey();
}
}
I measured the time needed for a few millions overload calls and optional parameter calls.
optional parameters with strings: 18 % slower (2 parameters, release)
optional parameters with ints: <1 % faster (2 parameters, release)
(And maybe compilers optimize or will optimize those optional parameter calls in future ?)
I just did a quick test and the compiler optimizes the code. This basic example Main method.
public static void OptionalParamMethod(bool input, string input2 = null)
{
}
public static void Main(string[] args)
{
OptionalParamMethod(true);
OptionalParamMethod(false, "hello");
}
Compiles to this so the optional params are filled in by the compiler.
public static void Main(string[] args)
{
OptionalParamMethod(true, null);
OptionalParamMethod(false, "hello");
}
As for performance you could argue optional parameters have a slight advantage as there is only a single method call rather than chained method calls like you would normally have for an overloaded method. The code below is compiled output to show what I am talking about. The difference is quite academic though and I doubt you would ever notice in practice.
public static void Main(string[] args)
{
OptionalParamMethod(true, null);
OptionalParamMethod(false, "hello");
OverloadParamMethod(true);
OverloadParamMethod(false, "hello");
}
public static void OptionalParamMethod(bool input, [Optional, DefaultParameterValue(null)] string input2)
{
Console.WriteLine("OptionalParamMethod");
}
public static void OverloadParamMethod(bool input)
{
OverloadParamMethod(input, null);
}
public static void OverloadParamMethod(bool input, string input2)
{
Console.WriteLine("OverloadParamMethod");
}
Neither overloading nor optional parameters will in themselves cause any changes in performance. As David Ewen noted, the C# compiler produces IL that does not know about optional parameters (this is the sources of some versioning bugs that come from optional parameters on types which can be literal).
As for overloading. C# is a (mostly) statically typed language. The compiled code directly references the address of the appropriate method. There is a small performance hit when overloading AT COMPILE time. In C++ in fact, overloading is done by a process called "name mangling" where each overload at compile time is given a unique name.
However there are cases where overloading CAN impact performance. But these are pretty obvious, like during reflection and in dynamic typed code.
It sounds like you are confused about the performance hit of virtual/abstract functions. In order for the .net runtime to resolve the correct function, there is an extra step which looks up the particular type's implementation of that method.

C# - Can someone tell me why and where I should use delegates? [duplicate]

This question already has answers here:
Where do I use delegates? [closed]
(8 answers)
Closed 9 years ago.
I think I understand the concept of a delegate in C# as a pointer to a method, but I cant find any good examples of where it would be a good idea to use them. What are some examples that are either significantly more elegant/better with delegates or cant be solved using other methods?
The .NET 1.0 delegates:
this.myButton.Click += new EventHandler(this.MyMethod);
The .NET 2.0 delegates:
this.myOtherButton.Click += delegate {
var res = PerformSomeAction();
if(res > 5)
PerformSomeOtherAction();
};
They seem pretty useful. How about:
new Thread(new ThreadStart(delegate {
// do some worker-thread processing
})).Start();
What exactly do you mean by delegates? Here are two ways in which they can be used:
void Foo(Func<int, string> f) {
//do stuff
string s = f(42);
// do more stuff
}
and
void Bar() {
Func<int, string> f = delegate(i) { return i.ToString(); }
//do stuff
string s = f(42);
// do more stuff
}
The point in the second one is that you can declare new functions on the fly, as delegates. This can be largely replaced by lambda expressions,and is useful any time you have a small piece of logic you want to 1) pass to another function, or 2) just execute repeatedly. LINQ is a good example. Every LINQ function takes a lambda expression as its argument, specifying the behavior. For example, if you have a List<int> l then l.Select(x=>(x.ToString()) will call ToString() on every element in the list. And the lambda expression I wrote is implemented as a delegate.
The first case shows how Select might be implemented. You take a delegate as your argument, and then you call it when needed. This allows the caller to customize the behavior of the function. Taking Select() as an example again, the function itself guarantees that the delegate you pass to it will be called on every element in the list, and the output of each will be returned. What that delegate actually does is up to you. That makes it an amazingly flexible and general function.
Of course, they're also used for subscribing to events. In a nutshell, delegates allow you to reference functions, using them as argument in function calls, assigning them to variables and whatever else you like to do.
I primarily use the for easy asynch programming. Kicking off a method using a delegates Begin... method is really easy if you want to fire and forget.
A delegate can also be used like an interface when interfaces are not available. E.g. calling methods from COM classes, external .Net classes etc.
Events are the most obvious example. Compare how the observer pattern is implemented in Java (interfaces) and C# (delegates).
Also, a whole lot of the new C# 3 features (for example lambda expressions) are based on delegates and simplify their usage even further.
For example in multithread apps. If you want several threads to use some control, You shoul use delegates. Sorry, the code is in VisualBasic.
First you declare a delegate
Private Delegate Sub ButtonInvoke(ByVal enabled As Boolean)
Write a function to enable/disable button from several threads
Private Sub enable_button(ByVal enabled As Boolean)
If Me.ButtonConnect.InvokeRequired Then
Dim del As New ButtonInvoke(AddressOf enable_button)
Me.ButtonConnect.Invoke(del, New Object() {enabled})
Else
ButtonConnect.Enabled = enabled
End If
End Sub
I use them all the time with LINQ, especially with lambda expressions, to provide a function to evaluate a condition or return a selection. Also use them to provide a function that will compare two items for sorting. This latter is important for generic collections where the default sorting may or may not be appropriate.
var query = collection.Where( c => c.Kind == ChosenKind )
.Select( c => new { Name = c.Name, Value = c.Value } )
.OrderBy( (a,b) => a.Name.CompareTo( b.Name ) );
One of the benefits of Delegates is in asynchronous execution.
when you call a method asynchronously you do not know when it will finish executing, so you need to pass a delegate to that method that point to another method that will be called when the first method has completed execution. In the second method you can write some code that inform you the execution has completed.
Technically delegate is a reference type used to encapsulate a method with a specific signature and return type
Some other comments touched on the async world... but I'll comment anyway since my favorite 'flavor' of doing such has been mentioned:
ThreadPool.QueueUserWorkItem(delegate
{
// This code will run on it's own thread!
});
Also, a huge reason for delegates is for "CallBacks". Let's say I make a bit of functionality (asynchronously), and you want me to call some method (let's say "AlertWhenDone")... you could pass in a "delegate" to your method as follows:
TimmysSpecialClass.DoSomethingCool(this.AlertWhenDone);
Outside of their role in events, which your probably familiar with if you've used winforms or asp.net, delegates are useful for making classes more flexible (e.g. the way they're used in LINQ).
Flexibility for "Finding" things is pretty common. You have a collection of things, and you want to provide a way to find things. Rather than guessing each way that someone might want to find things, you can now allow the caller to provide the algorithm so that they can search your collection however they see fit.
Here's a trivial code sample:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegates
{
class Program
{
static void Main(string[] args)
{
Collection coll = new Collection(5);
coll[0] = "This";
coll[1] = "is";
coll[2] = "a";
coll[3] = "test";
var result = coll.Find(x => x == "is");
Console.WriteLine(result);
result = coll.Find(x => x.StartsWith("te"));
Console.WriteLine(result);
}
}
public class Collection
{
string[] _Items;
public delegate bool FindDelegate(string FindParam);
public Collection(int Size)
{
_Items = new string[Size];
}
public string this[int i]
{
get { return _Items[i]; }
set { _Items[i] = value; }
}
public string Find(FindDelegate findDelegate)
{
foreach (string s in _Items)
{
if (findDelegate(s))
return s;
}
return null;
}
}
}
Output
is
test
there isn't really anything delgates will solve that can't be solved with other methods, but they provide a more elegant solution.
With delegates, any function can be used as long as it has the required parameters.
The alternative is often to use a kind of custom built event system in the program, creating extra work and more areas for bugs to creep in
Is there an advantage to use a delegate when dealing with external calls to a database?
For example can code A :
static void Main(string[] args) {
DatabaseCode("test");
}
public void DatabaseCode(string arg) {
.... code here ...
}
Be improved in code B :
static void Main(string[] args) {
DatabaseCodeDelegate slave = DatabaseCode;
slave ("test");
}
public void DatabaseCode(string arg) {
.... code here ...
}
public delegate void DatabaseCodeDelegate(string arg);
It seems that this is subjective, but an area where there are strong conflicting view points?

Categories

Resources