Click here to Skip to main content
15,887,485 members
Home / Discussions / C#
   

C#

 
GeneralRe: The dates of the next week and the previous week days Pin
OriginalGriff5-Apr-14 6:12
mveOriginalGriff5-Apr-14 6:12 
GeneralRe: The dates of the next week and the previous week days Pin
ismail205-Apr-14 6:12
ismail205-Apr-14 6:12 
QuestionAnonymous or static or lambda methods?? Pin
Sea_Sharp4-Apr-14 8:56
Sea_Sharp4-Apr-14 8:56 
AnswerRe: Anonymous or static or lambda methods?? Pin
Mycroft Holmes4-Apr-14 14:20
professionalMycroft Holmes4-Apr-14 14:20 
AnswerRe: Anonymous or static or lambda methods?? Pin
OriginalGriff4-Apr-14 20:55
mveOriginalGriff4-Apr-14 20:55 
GeneralRe: Anonymous or static or lambda methods?? Pin
Richard Deeming7-Apr-14 1:57
mveRichard Deeming7-Apr-14 1:57 
GeneralRe: Anonymous or static or lambda methods?? Pin
Sea_Sharp7-Apr-14 2:57
Sea_Sharp7-Apr-14 2:57 
GeneralRe: Anonymous or static or lambda methods?? Pin
OriginalGriff7-Apr-14 5:33
mveOriginalGriff7-Apr-14 5:33 
A delegate doesn't have to be a lambda or anonymous function - it can be a named function as well: in fact it can be a list of functions, provided the method signature matches the delegate template and all of them will be called.
Try it:
C#
public delegate int MyDelegate(string x);
public MyDelegate theDelegate;


C#
    theDelegate += (x) => {Console.WriteLine("Lambda {0}", x); return x.Length; };
    theDelegate += delegate(string x) { Console.WriteLine("Anonymous {0}", x); return x.Length; };
    theDelegate += Named;
    theDelegate("hello");
    }
private int Named(string x)
    {
    Console.WriteLine("Named {0}", x);
    return x.Length;
    }
And you will get:
C#
Lambda hello
Anonymous hello
Named hello
So you can use delegates to "chain" methods together - and in fact you use this all the time: delegates are what makes Events work!

So yes, in a way a delegate is a "contract" in that it specifies the method signature which it can accept - but don't really think of it like that, because it's main task is as a function pointer: it allows you to write code that doesn't need to know exactly what it is calling, just that "it takes these parameters and it returns such-and-such". So it would be (relatively) easy to write code which used delegates to work (seamlessly) with SQL Server, MySql and CSV files - without the code needing to know what kind of storage medium is behind it: it just calls the "write this to this table" and "get this from that table" delegates and the outside world sorts out the actual code to do that. Without delegates, you couldn't do that in C# - you have to write code which explicitly checked:
C#
if (usingMSSQL) ReadFromMsSQL(table, columnlist);
else if (usingMySQL) ReadFromMySQL(table, columnlist);
else if (usingCSV) ReadFromCSV(table, columnlist);
else Throw new IDontKnowWhatToDoException("HELP!");
ANd write similar code for every other method you need: INSERT, DELETE, UPDATE, and so forth. Then to add another (Excel perhaps) you have to change the code to support it - and risk missing one, or messing up, or otherwise getting it wrong.

OK, that's an advanced form, that you probably won't need to use for years, if ever - but Events are handled via exactly the same mechanism - and it just isn't possible to "add methods" to .NET code to include your event handler methods because (most of us) didn't even have access to the .NET source until fairly recently.
So accept delegates as needed, and we'll go from there.

So why use anonymous functions and lambdas at all? Well, if your code is tiny, you can improve the readability of your code by including it inline:
C#
theDelegate += delegate(string x) { Console.WriteLine("Anonymous {0}", x); return x.Length + 1; };
instead of:
C#
theDelegate += delegate(string x) { PrintItAndGetLength(x); };
when PrintItAndGetLength is miles away or in a different file completely - it breaks your concentration to go there, look ate the method, find it does two simple things, and then come back to continue reading. Since this code isn't going to be used anywhere else, it's simpler and easier just to use an anonymous method - especially as most of them are one line of code, is all. (Certainly in the real world I wouldn't use two lines of code or more in an anonymous method - I'd move it to a named method).

So why lambdas? Ah...well.
The delegate syntax is clumsy, and messy, and Microsoft wanted to introduce Linq - which really, really needs anonymous methods - because you can use anonymous classes within Linq, which means you can't write a named method to use them at all!

So they invented Lambdas to "clean up" the syntax: the lambda is a generic (but strongly typed) delegate that doesn't need an external delegate to define the method signature - it is inferred from usage (as is var, which was invented at the same time and for exactly the same reason).

And now you can use Linq in a clean, tidy way:
C#
List<int> myList = new List<int>() { 1, 2, 4, 7, 2, 13, 16, 5 };
var output = myList.Where(x => x < 6).Distinct().OrderBy(x => x).Select(x => x.ToString());
In that one line of code you have three delegates none of which require any external declarations, and you can see immediately what it all does: Selects only items less than 6, throws away duplicates, sorts by the value itself, and the converts each of them to a string, before returning a collection of the strings.

The equivalent "true delegate" code would be a lot longer, and a lot, lot harder to read. And as I mentioned - sometimes you can't even declare an instance of the class, because you can create anonymous classes in Linq! So you can't use named methods even if you wanted to!

I'm going to stop there, for the moment - that's way too long! Laugh | :laugh:
Those who fail to learn history are doomed to repeat it. --- George Santayana (December 16, 1863 – September 26, 1952)
Those who fail to clear history are doomed to explain it. --- OriginalGriff (February 24, 1959 – ∞)

GeneralRe: Anonymous or static or lambda methods?? Pin
Sea_Sharp7-Apr-14 8:34
Sea_Sharp7-Apr-14 8:34 
GeneralRe: Anonymous or static or lambda methods?? Pin
OriginalGriff7-Apr-14 8:52
mveOriginalGriff7-Apr-14 8:52 
QuestionRetrieving a List of Contacts from Exchange Pin
Member 103181264-Apr-14 1:05
Member 103181264-Apr-14 1:05 
AnswerRe: Retrieving a List of Contacts from Exchange Pin
OriginalGriff4-Apr-14 2:34
mveOriginalGriff4-Apr-14 2:34 
QuestionLinkedin import to C# WPF desktop application? Pin
Mandarinna3-Apr-14 23:42
Mandarinna3-Apr-14 23:42 
AnswerRe: Linkedin import to C# WPF desktop application? Pin
Richard MacCutchan3-Apr-14 23:58
mveRichard MacCutchan3-Apr-14 23:58 
QuestionTCPClient across AppDomains Pin
Carlos Sousa3-Apr-14 23:38
Carlos Sousa3-Apr-14 23:38 
AnswerRe: TCPClient across AppDomains Pin
Rob Philpott4-Apr-14 4:27
Rob Philpott4-Apr-14 4:27 
GeneralRe: TCPClient across AppDomains Pin
Carlos Sousa4-Apr-14 5:15
Carlos Sousa4-Apr-14 5:15 
GeneralRe: TCPClient across AppDomains Pin
Rob Philpott4-Apr-14 6:03
Rob Philpott4-Apr-14 6:03 
GeneralRe: TCPClient across AppDomains Pin
Carlos Sousa4-Apr-14 11:37
Carlos Sousa4-Apr-14 11:37 
AnswerRe: TCPClient across AppDomains Pin
jschell4-Apr-14 8:15
jschell4-Apr-14 8:15 
GeneralRe: TCPClient across AppDomains Pin
Carlos Sousa4-Apr-14 11:45
Carlos Sousa4-Apr-14 11:45 
GeneralRe: TCPClient across AppDomains Pin
jschell7-Apr-14 9:23
jschell7-Apr-14 9:23 
GeneralRe: TCPClient across AppDomains Pin
Carlos Sousa8-Apr-14 5:33
Carlos Sousa8-Apr-14 5:33 
GeneralRe: TCPClient across AppDomains Pin
Carlos Sousa9-Apr-14 3:35
Carlos Sousa9-Apr-14 3:35 
GeneralRe: TCPClient across AppDomains Pin
jschell10-Apr-14 8:30
jschell10-Apr-14 8:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.