I have a delegate defined in my code:  public bool delegate CutoffDateDelegate( out DateTime cutoffDate );   I would like to create delegate and initialize with a lambda or anonymous function, but neither of these compiled.  CutoffDateDelegate del1 = dt =&gt; { dt = DateTime.Now; return true; } CutoffDateDelegate del2 = delegate( out dt ) { dt = DateTime.Now; return true; }   Is there way to do this?
100125
The following method does not compile. Visual Studio warns "An out parameter may not be used within an anonymous method". The WithReaderLock(Proc action) method takes a delegate void Proc().  public Boolean TryGetValue(TKey key, out TValue value) {     Boolean got = false;     WithReaderLock(delegate     {         got = dictionary.TryGetValue(key, out value);     });     return got; }   What's the best way to get this behavior? (Please refrain from providing advice on threadsafe dictionaries, this question is intended to solve the out parameter problem in general).
96847
I have a code sample that gets a SEL from the current object,   SEL callback = @selector(mymethod:parameter2);   And I have a method like    -(void)mymethod:(id)v1 parameter2;(NSString*)v2 { }   Now I need to move mymethod to another object, say myDelegate.  I have tried:  SEL callback = @selector(myDelegate, mymethod:parameter2);   but it won't compile.
55107
What is the difference between anonymous methods of C# 2.0 and lambda expressions of C# 3.0.?
64302
I frequently find myself writing code like this:  List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 }; foreach (int i in list) {     Console.Write("{0}\t", i.ToString()); } Console.WriteLine();   Better would be something like this:  List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 }; Console.WriteLine("{0}\t", list);   I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block?
80489
There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other.  First type:  List&lt;string&gt; someList = &lt;some way to init&gt; foreach(string s in someList) {    &lt;process the string&gt; }   Other Way:  List&lt;string&gt; someList = &lt;some way to init&gt; someList.ForEach(delegate(string s) {     &lt;process the string&gt; });   I suppose off the top of my head, that instead of the anonymous delegate I use above, you'd have a reusable delegate you could specify...
24567
I am trying to determine what issues could be caused by using the following serialization surrogate to enable serialization of anonymous functions/delegate/lambdas.   // see http://msdn.microsoft.com/msdnmag/issues/02/09/net/#S3 class NonSerializableSurrogate : ISerializationSurrogate {     public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)     {         foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))             info.AddValue(f.Name, f.GetValue(obj));     }      public object SetObjectData(object obj, SerializationInfo info, StreamingContext context,                                 ISurrogateSelector selector)     {         foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))             f.SetValue(obj, info.GetValue(f.Name, f.FieldType));         return obj;     } }     Listing 1 adapted from   The main issue I can think of that might be a problem is that the anonymous class is an internal compiler detail and it's structure is not guaranteed to remain constant between revisions to the .NET Framework. I'm fairly certain this is the case based on my research into the similar problem with iterators.  Background  I am investigating the serialization of anonymous functions. I was expecting this not to work, but found it did for some cases. As long as the lambda did *not&amp; force the compiler to generate an anonymous class everything works fine.   A SerializationException is thrown if the compiler requires a generated class to implement the anonymous function. This is because the compiler generated class is not marked as serializable.  Example  namespace Example {     [Serializable]     class Other     {         public int Value;     }      [Serializable]     class Program     {         static void Main(string[] args)         {             MemoryStream m = new MemoryStream();             BinaryFormatter f = new BinaryFormatter();              // Example 1             Func&lt;int&gt; succeeds = () =&gt; 5;             f.Serialize(m, succeeds);              // Example 2             Other o = new Other();             Func&lt;int&gt; fails = () =&gt; o.Value;             f.Serialize(m, fails); // throws SerializationException - Type 'Example.Program+&lt;&gt;c__DisplayClass3' in Assembly 'Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.         }     }   Listing 2  This is similar to the issue of trying to serialize iterators and I had found the following code in a previous search (see ) Using the code from Listing 1 and an ISurrogateSelector I was able to successfully serialize and deserialize the second failing example.  Objective  I have a system that is exposed via a web service. The system has a complex but small state (many objects, not a lot of properties per object). The state is saved in the ASP.NET Cache, but is also serialized to a BLOB in SQL in case of cache expiration. Some objects need to execute arbitrary "events" upon reaching some condition. Hence they have properties accepting Action/Func objects. Contrived example:      class Command     {         public Command(Action action, Func&lt;bool&gt; condition);     }   Somewhere else      void DoSomethingWithThing(Thing thing)     {         state = Store.GetCurrentState();          Command cmd = new Command(() =&gt; thing.Foo(), () =&gt; thing.IsReady())         state.Add(cmd);          Store.Save(state);     }
90864
I very rarely meet any other programmers!  My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense.  So how do I say or read "=>" as in:-  IEnumerable&lt;Person&gt; Adults = people.Where(p =&gt; p.Age &gt; 16)   Or is there even an agreed way of saying it?
56347
The  keyword does away with the need for an explicit type declaration and I have read with interest the  of when it might be appropriate.  I have also read about (but not used)  which seems to take things a step further by making it .  With Boo, both the type and the declaration can be implied.  Which leads me to wonder, why did the C# language designers bother to include a var keyword at all?    Update: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword...  var anon = new { Name = "Terry", Age = 34 };   versus  anon = new { Name = "Terry", Age = 34 };
24836
Given a method signature:  public bool AreTheSame&lt;T&gt;(Expression&lt;Func&lt;T, object&gt;&gt; exp1, Expression&lt;Func&lt;T, object&gt;&gt; exp2)   What would be the most efficient way to say if the two expressions are the same? This only needs to work for simple expressions, by this I mean all that would be "supported" would be simple MemberExpressions, eg c => c.ID.  An example call might be:  AreTheSame&lt;User&gt;(u1 =&gt; u1.ID, u2 =&gt; u2.ID); --&gt; would return true
101661
Just read a couple MSO posts about editing guidelines, after seeing  getting rejected.  I had stumbled upon an old question that somehow made it onto the front page, and saw a great answer there. The question was about "understanding events and event handlers in C#", and the answer was great but there was further information in the comments.  So I started editing the post; I found that "if we create a delegate void MyDelegate(object sender, EventArgs e)" was clearer if the backtick encompassed the delegate word, so I moved it.  A commenter was asking "How is the event fired?", and the answerer replied with a comment instead of editing his answer, so I added a code snippet to give an example of how the event would be fired.  Then I noticed the code block actually included two parts that really belonged in two separate classes (the one where the event is created, and the one where the event is registered/handled), so I split the definition and the consumption of the event into two code blocks. That made it much clearer what belonged where, even though there weren't any classes involved (didn't add any).  And then I added the part why I actually wanted to edit the post in the first place: I added the shorthand notation for registering events: myObj.SomethingHappened += HandleSomethingHappened;. I left the full notation in place.  And lastly I added a line of code to show how a handler could be unregistered with -=.  As the first reviewer approved the edit, I thought to myself "hmm this last paragraph I added to introduce the -= really just restates the previous one from the original author" - shortly after that, my edit was rejected by 3 reviewers in a row.  The reason was "This edit is incorrect or an attempt to reply to or comment on the existing post." -- really? Is this how constructive edits are being welcomed? Have I introduced bad code that's just plain wrong? I mean, I use the shorthand notation all the time, I know it's correct. The -= part was just added for the sake of completeness, and the backtick would have been too minor of an edit. Reordering the code snippets and splitting them in two distinct blocks really improves the post I find, but someone who just glanced at the diff could think I removed the event handler snippet, when I merely cut it &amp; pasted it below the event registration code.  So I'm guessing the redundant paragraph killed it? Should I submit another edit, minus that paragraph? Actually I don't even care, it's a question from 2009 with almost 60K views and the answer is great enough as it is to have received 155 upvotes (plus mine), and if people don't know they don't need to new up the delegate to register the event then they can just buy ReSharper and have the tool teach them it's redundant. And if they want to unregister a handler then they can certainly find how to do that somewhere else. And maybe I should be doing something else to kill my spare time than browsing SO and upvoting good questions and answers, downvoting and flagging bad ones, and improve the few posts I can contribute to with the few things I do know. I mean, I intended to genuinely improve an excellent post, it's a bit (quite) irritating to read it's an "incorrect" edit.  I take the [Reject] edits that change an answer's explanation or code, with a supposedly "better" alternative. Even if the proposed solution is better, it should be added as a comment, or a separate answer. guideline as what caused my edit to be rejected. Point is, I was adding information to the answer, not changing or replacing anything.  So, was this edit legit? If I understand  correctly, my edit should have been rejected for changing too much of the post, not for being incorrect or an attempt to comment on the answer. And if Servy's MSO answer is still right, it means I should have posted my content as a brand new answer... to a question that's like 4 years old? , but I find it would have been better to just edit the post, given that "Edits are expected to be substantial and to leave the post better than you found it."  Sorry for the long post.
78162
I collect a few corner cases and  and would always like to hear more. The page only really covers C# language bits and bobs, but I also find core .NET things interesting too. For example, here's one which isn't on the page, but which I find incredible:  string x = new string(new char[0]); string y = new string(new char[0]); Console.WriteLine(object.ReferenceEquals(x, y));   I'd expect that to print False - after all, "new" (with a reference type) always creates a new object, doesn't it? The specs for both C# and the CLI indicate that it should.  Well, not in this particular case. It prints True, and has done on every version of the framework I've tested it with. (I haven't tried it on Mono, admittedly...)  Just to be clear, this is only an example of the kind of thing I'm looking for - I wasn't particularly looking for discussion/explanation of this oddity. (It's not the same as normal string interning; in particular, string interning doesn't normally happen when a constructor is called.) I was really asking for similar odd behaviour.  Any other gems lurking out there?
7075
I have a function which parses one string into two strings.  In C# I would declare it like this:  void ParseQuery(string toParse, out string search, out string sort) {     ... }   and I'd call it like this:  string searchOutput, sortOutput; ParseQuery(userInput, out searchOutput, out sortOutput);   The current project has to be done in C++/CLI.  I've tried  using System::Runtime::InteropServices;  ...  void ParseQuery(String ^ toParse, [Out] String^ search, [Out] String^ sort) {     ... }   but if I call it like this:  String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, [Out] searchOutput, [Out] sortOutput);   I get a compiler error, and if I call it like this:  String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, searchOutput, sortOutput);   then I get an error at runtime.  How should I declare and call my function?
11352
Duplicate:     Maybe this is a very silly question but I don't understand why I can't declare two methods that have the same signature when they have different return types.  public class MyClass {     private double d = 0;      public double MyMethod()     {         return d;     }      public string MyMethod()     {         return d.ToString();     } }   I get a compile error that states that the class already defines a member with the same parameter types.  (Obviously the way I'm using this in my code isn't as simple as my example code...but I think it gets the idea across.)  Am I missing something concerning OO design that makes what I'm trying to do an OOP anti-pattern? Surely the compiler should be able to determine which method I'm trying to use as long as I specifically tell it which one I want.  Given MyClass myClass = new MyClass(); I would expect the following code to work:  double d = myClass.MyMethod(); string s = myClass.MyMethod();   I would expect the following code to have problems:  var v = myClass.MyMethod();   But even in the case of var it should result in a compile error.  Can anyone see what I'm doing wrong here? I'm more than happy to be corrected. :-)
51956
For creating a list template programmatically by using server object, I'm using the SaveAsTemplate() function.  SPSecurity.RunWithElevatedPrivileges(delegate {   using (SPSite oSPsite = new SPSite(strSiteURL))   {     oSPsite.AllowUnsafeUpdates = true;     using (SPWeb oSPWeb = oSPsite.OpenWeb())     {       oSPWeb.AllowUnsafeUpdates = true;        SPList list = oSPWeb.Lists[strListName];       string bkpTemplateName = "bkp" + strListName + ".stp";       list.SaveAsTemplate(bkpTemplateName, bkpTemplateName.Replace(".stp",""), "Description", true);        list.Update();       oSPWeb.AllowUnsafeUpdates = false;     }     oSPsite.AllowUnsafeUpdates = false;   } });   But, is there a way to do the same by using CSOM?
83564
I know VB.Net and am trying to brush up on my C#.  Is there a With block equivalent in C#?  Thanks
14396
For years, I've been using named blocks to limit the scope of temporary variables.  I've never seen this done anywhere else, which makes me wonder if this is a bad idea.  Especially since the Eclipse IDE flags these as warnings by default.  I've used this to good effect, I think, in my own code.  But since it is un-idiomatic to the point where good programmers will distrust it when they see it, I really have two ways to go from here:     avoid doing it, or  promote it, with the hope that it will become an idiom.   Example (within a larger method):  final Date nextTuesday; initNextTuesday: {     GregorianCalendar cal = new GregorianCalendar();     ... // About 5-10 lines of setting the calendar fields     nextTuesday = cal.getTime(); }   Here I'm using a GregorianCalendar just to initialize a date, and I want to make sure that I don't accidentally reuse it.  Some people have commented that you don't actually need to name the block.  While that's true, a raw block looks even more like a bug, as the intent is unclear.  Furthermore, naming something encourages you to think about the intention of the block.  The goal here is to identify distinct sections of code, not to give every temporary variable its own scope.  Many people have commented that it's best to go straight to small methods.  I agree that this should be your first instinct.  However, there may be several mitigating factors:   To even consider a named block, the code should be short, one-off code that will never be called elsewhere. A named block is a quick way to organize an oversized method without creating a one-off method with a dozen parameters.  This is especially true when a class is in flux, and the inputs are likely to change from version to version. Creating a new method encourages its reuse, which may be ill-advised if the use cases aren't well-established.  A named block is easier (psychologically, at least) to throw away. Especially for unit tests, you may need to define a dozen different objects for one-off assertions, and they are just different enough that you can't (yet) find a way to consolidate them into a small number of methods, nor can you think of a way to distinguish them with names that aren't a mile long.   Advantages of using the named scope:   Can't accidentally reuse temporary variables Limited scope gives garbage collector and JIT compiler more information about programmer intent Block name provides a comment on a block of code, which I find more readable than open-ended comments Makes it easier to refactor code out of a big method into little methods, or vice versa, since the named block is easier to separate than unstructured code.   Disadvantages:  Not idiomatic: programmers who haven't seen this use of named blocks (i.e. everyone but me) assume it's buggy, since they can't find references to the block name.  (Just like Eclipse does.)  And getting something to become idiomatic is an uphill battle.  It can be used as an excuse for bad programming habits, such as:   Making huge, monolithic methods where several small methods would be more legible. Layers of indentation too deep to read easily.   Note:  I've edited this question extensively, based on some thoughtful responses.  Thanks!
44387
I am looking for good ideas for implementing a generic way to have a single line (or anonymous delegate) of code execute with a timeout.  TemperamentalClass tc = new TemperamentalClass(); tc.DoSomething();  // normally runs in 30 sec.  Want to error at 1 min   I'm looking for a solution that can elegantly be implemented in many places where my code interacts with temperamental code (that I can't change).  In addition, I would like to have the offending "timed out" code stopped from executing further if possible.