How do I make parameter that will accept (x =&gt; x.Value) like .Sum(x =&gt; x.Value) or .Average(x =&gt; x.Value). I'm thinking I need it to be a Func&lt;&gt; but I'm not sure.  I don't know what the method signature should look. Here's what my current extension method looks like: public static double StdDev(this IEnumerable&lt;double&gt; values) {     //code }  Here's my overload extension so far based (I know this isn't right): public static double StdDev(this IEnumerable&lt;double&gt; values, Func&lt;double, bool&gt; filter) {     IEnumerable&lt;double&gt; data;     if (filter != null)     {         data = values.Where(filter);     }     else     {         data = values;     }     return data.StdDev(); }  Here's my unit test: [TestClass] public class IEnumerableExtensions_StdDev {     [TestMethod]     public void StdDev_Success_Lambda()     {         var dataSet = new List&lt;TestType&gt; {new TestType(35.2), new TestType(54.43)};          //This Line compiles fine but the following one does not.         var test = dataSet.Sum(x =&gt; x.Value);         var stdev = dataSet.StdDev(x =&gt; x.Value);          stdev.Should().BeInRange(13.5, 13.6);     } }  public class TestType {     public double Value { get; set; }      public TestType(double value)     {         Value = value;     } }  The unit test does not compile.  It gives me an error that reads:  'List' does not contain a definition for 'StdDev' and the best extension method overload 'IEnumerableExtensions.StdDev(IEnumerable, Func&lt;double, bool&gt;)' requires a receiver of type 'IEnumerable'  I don't want to change the test I want to change the overload method signature and/or body but I don't understand what I need to change in my code to make this work.
16712
Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).  We're building a web API that's programmatically generated from a C# class. The class has method GetFooBar(int a, int b) and the API has a method GetFooBar taking query params like &amp;a=foo &amp;b=bar.   The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?
103793
I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1:  T createDefault() {     if(typeof(T).IsValueType)     {         return default(T);     }     else     {         return Activator.CreateInstance&lt;T&gt;();     } }   Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is:  T createDefault() {     if(typeof(T).IsValueType || typeof(T).FullName == "System.String")     {         return default(T);     }     else     {         return Activator.CreateInstance&lt;T&gt;();     } }   But this feels like a kludge. Is there a nicer way to handle the string case?
36770
If I have a string with a valid math expression such as:  String s = "1 + 2 * 7";   Is there a built in library/function in .NET that will parse and evaluate that expression for me and return the result? In this case 15.
33704
I want to compose the results of two Linq Expressions. They exist in the form  Expression&lt;Func&lt;T, bool&gt;&gt;   So the two that I want to compose are essentially delegates on a parameter (of type T) that both return a boolean. The result I would like composed would be the logical evaluation of the booleans. I would probably implement it as an extension method so my syntax would be something like:  Expression&lt;Func&lt;User, bool&gt;&gt; expression1 = t =&gt; t.Name == "steve"; Expression&lt;Func&lt;User, bool&gt;&gt; expression2 = t =&gt; t.Age == 28; Expression&lt;Func&lt;User, bool&gt;&gt; composedExpression = expression1.And(expression2);   And later on in my code I want to evaluate the composed expression  var user = new User(); bool evaluated = composedExpression.Compile().Invoke(user);   I have poked around with a few different ideas but I fear that it is more complex than I had hoped. How is this done?
15230
example:  public static void DoSomething&lt;K,V&gt;(IDictionary&lt;K,V&gt; items) {    items.Keys.Each(key =&gt; {       if (items[key] **is IEnumerable&lt;?&gt;**) { /* do something */ }       else { /* do something else */ } }   Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable&lt;> implements IEnumerable?
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
90873
I have an Enumerable&lt;T&gt; and am looking for a method that allows me to execute an action for each element, kind of like Select but then for side-effects. Something like:  string[] Names = ...; Names.each(s =&gt; Console.Writeline(s));   or   Names.each(s =&gt; GenHTMLOutput(s));    // (where GenHTMLOutput cannot for some reason receive the enumerable itself as a parameter)   I did try Select(s=&gt; { Console.WriteLine(s); return s; }), but it wasn't printing anything.
20538
I'm attempting to use extension methods to add an operater overload to the C# StringBuilder class.  Specifically, given StringBuilder sb, I'd like sb += "text" to become equivalent to sb.Append("text").  Here's the syntax for creating an extension method for StringBuilder:  public static class sbExtensions {     public static StringBuilder blah(this StringBuilder sb)     {         return sb;     } }    It successfully adds the blah extension method to the StringBuilder.  Unfortunately, operator overloading does not seem to work:  public static class sbExtensions {     public static StringBuilder operator +(this StringBuilder sb, string s)     {         return sb.Append(s);     } }    Among other issues, the keyword this is not allowed in this context.  Are adding operator overloads via extension methods possible?  If so, what's the proper way to go about it?
33470
What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading.   What is the best way to achieve this?
75761
I'd like to do the equivalent of the following in LINQ, but I can't figure out how:  IEnumerable&lt;Item&gt; items = GetItems(); items.ForEach(i =&gt; i.DoStuff());   What is the real syntax?
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).
104904
I really should be able to get this, but I'm just to the point where I think it'd be easier to ask.  In the C# function:  public static T GetValue&lt;T&gt;(String value) where T:new() {    //Magic happens here }   What's a good implementation for the magic? The idea behind this is that I have xml to parse and the desired values are often primitives (bool, int, string, etc.) and this is the perfect place to use generics... but a simple solution is eluding me at the moment.  btw, here's a sample of the xml I'd need to parse  &lt;Items&gt;     &lt;item&gt;         &lt;ItemType&gt;PIANO&lt;/ItemType&gt;         &lt;Name&gt;A Yamaha piano&lt;/Name&gt;         &lt;properties&gt;             &lt;allowUpdates&gt;false&lt;/allowUpdates&gt;             &lt;allowCopy&gt;true&lt;/allowCopy&gt;         &lt;/properties&gt;        &lt;/item&gt;     &lt;item&gt;         &lt;ItemType&gt;PIANO_BENCH&lt;/ItemType&gt;         &lt;Name&gt;A black piano bench&lt;/Name&gt;         &lt;properties&gt;             &lt;allowUpdates&gt;true&lt;/allowUpdates&gt;             &lt;allowCopy&gt;false&lt;/allowCopy&gt;             &lt;url&gt;www.yamaha.com&lt;/url&gt;         &lt;/properties&gt;     &lt;/item&gt;     &lt;item&gt;         &lt;ItemType&gt;DESK_LAMP&lt;/ItemType&gt;         &lt;Name&gt;A Verilux desk lamp&lt;/Name&gt;         &lt;properties&gt;             &lt;allowUpdates&gt;true&lt;/allowUpdates&gt;             &lt;allowCopy&gt;true&lt;/allowCopy&gt;             &lt;quantity&gt;2&lt;/quantity&gt;         &lt;/properties&gt;     &lt;/item&gt; &lt;/Items&gt;
42281
I have a controller with an action method as follows:  public class InventoryController : Controller {     public ActionResult ViewStockNext(int firstItem)     {         // Do some stuff     } }   And when I run it I get an error stating:     The parameters dictionary does not contain a valid value of type 'System.Int32' for parameter 'firstItem'. To make a parameter optional its type should either be a reference type or a Nullable type.   I had it working at one point and I decided to try the function without parameters.  Finding out that the controller was not persistant I put the parameter back in, now it refuses to recognise the parameter when I call the method.  I'm using this url syntax to call the action:  http://localhost:2316/Inventory/ViewStockNext/11   Any ideas why I would get this error and what I need to do to fix it?   I've tried adding another method that takes an integer to the class it it also fails with the same reason.  I've tried adding one that takes a string, and the string is set to null.  I've tried adding one without parameters and that works fine, but of course it won't suit my needs.
95803
I'm having problems trying to overload the post increment operator in C#. Using integers we get the following results.  int n;  n = 10; Console.WriteLine(n); // 10 Console.WriteLine(n++); // 10 Console.WriteLine(n); // 11  n = 10; Console.WriteLine(n); // 10 Console.WriteLine(++n); // 11 Console.WriteLine(n); // 11   But, when I try it using classes, it looks like the objects are exchanged.  class Account {     public int Balance { get; set; }     public string Name { get; set; }      public Account(string name, int balance)     {         Balance = balance;         Name = name;     }      public override string ToString()     {         return Name + " " + Balance.ToString();     }      public static Account operator ++(Account a)     {         Account b = new Account("operator ++", a.Balance);         a.Balance += 1;         return b;     }      public static void Main()     {         Account a = new Account("original", 10);          Console.WriteLine(a); // "original 10"          Account b = a++;          Console.WriteLine(b); // "original 11", expected "operator ++ 10"         Console.WriteLine(a); // "operator ++ 10", expected "original 11"     } }   Debugging the application, the overloaded operator method, returns the new object with the old value (10) and the object that has been passed by reference, has the new value (11), but finally the objects are exchanged. Why is this happening?
2552
Possible Duplicate:          I've coded something like this:  public bool IsDataChanged() {                T value1 = GetValue2;     T value2 = GetValue1();      return (valueInDB != valueFromView); }   Right now the function doesn't compile with the error "Operator '!=' cannot be applied to operands of type 'T' and 'T'". What do I have to do to make this function work ?
58028
I want to do something like this :  myYear = record.GetValueOrNull&lt;int?&gt;("myYear"),   Notice the nullable type as the generic parameter.   Since the GetValueOrNull function could return null my first attempt was this:   public static T GetValueOrNull&lt;T&gt;(this DbDataRecord reader, string columnName)   where T : class {     object columnValue = reader[columnName];      if (!(columnValue is DBNull))     {         return (T)columnValue;     }     return null; }   But the error I'm getting now is:     The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method   Right! Nullable&lt;int&gt; is a struct! So I tried changing the class constraint to a struct constraint (and as a side effect can't return null any more):  public static T GetValueOrNull&lt;T&gt;(this DbDataRecord reader, string columnName)   where T : struct   Now the assignment:  myYear = record.GetValueOrNull&lt;int?&gt;("myYear");   Gives the following error:     The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method   Is specifying a nullable type as a generic parameter at all possible?
36889
Is it possible to have an anonymous type implement an interface?  I've got a piece of code that I would like to work, but don't know how to do this.  I've had a couple of answers that either say no, or create a class that implements the interface construct new instances of that. This isn't really ideal, but I'm wondering if there is a mechanism to create a thin dynamic class on top of an interface which would make this simple.  public interface DummyInterface {     string A { get; }     string B { get; } }  public class DummySource {     public string A { get; set; }     public string C { get; set; }     public string D { get; set; } }  public class Test {     public void WillThisWork()     {         var source = new DummySource[0];         var values = from value in source                      select new                      {                          A = value.A,                          B = value.C + "_" + value.D                      };          DoSomethingWithDummyInterface(values);      }      public void DoSomethingWithDummyInterface(IEnumerable&lt;DummyInterface&gt; values)     {         foreach (var value in values)         {             Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);         }     } }   I've found an article  that describes one approach. Is this the best way of doing this?