I'm currently trying to write an extension method to work out the allowed variance for a decimal. While I was writing it I thought I'd extend it to a generic extension, with restrictions to decimal, float, double.  Currently I'm not aware of how (or if it's possible) to restrict a generic to value types.  public static bool WithinVariance(this decimal source, decimal allowedVariance, decimal comparisonValue)         =&gt; WithinVariance&lt;decimal&gt;(source, allowedVariance, comparisonValue);  public static bool WithinVariance&lt;T&gt;(T source, T allowedVariance, T comparisonValue)     // where T : decimal     // where T : double     // where T : float  {     var allowedDifference = (source / 100) * allowedVariance;     var difference = source - comparisonValue;     return Math.Abs(difference) &lt;= allowedDifference; }   The above code doesn't work, it's there purely to show the approach I'm taking. Originally I was just going to a single method, but I changed to the above to try to hack it into working. Also an attempt at restricting the extension methods without using a where t filter (see commented out lines)  Does anyone know if it's possible and if so how to do this?
12964
Can anyone tell me if there is a way with generics to limit a generic type argument T to only:   Int16 Int32 Int64 UInt16 UInt32 UInt64   I'm aware of the where keyword, but can't find an interface for only these types,  Something like:  static bool IntegerFunction&lt;T&gt;(T value) where T : INumeric
81715
Edit:  Of course my real code doesn't look exactly like this. I tried to write semi-pseudo code to make it more clear of whay I wanted to do.  Looks like it just messed things up instead.  So, what I actually would like to do is this:  Method&lt;Interface1&gt;(); Method&lt;Interface2&gt;(); Method&lt;Interface3&gt;(); ...   Well ... I thought that maybe I could turn it into a loop using reflection. So the question is: How how do I do it. I have very shallow knowledge of reflection. So code examples would be great.  The scenario looks like this:  public void Method&lt;T&gt;() where T : class {} public void AnotherMethod() {     Assembly assembly = Assembly.GetExecutingAssembly();      var interfaces = from i in assembly.GetTypes()     where i.Namespace == "MyNamespace.Interface" // only interfaces stored here     select i;      foreach(var i in interfaces)     {         Method&lt;i&gt;(); // Get compile error here!     }       Original post:  Hi!  I'm trying to loop through all interfaces in a namespace and send them as arguments to a generic method like this:  public void Method&lt;T&gt;() where T : class {} public void AnotherMethod() {     Assembly assembly = Assembly.GetExecutingAssembly();      var interfaces = from i in assembly.GetTypes()     where i.Namespace == "MyNamespace.Interface" // only interfaces stored here     select i;      foreach(var interface in interfaces)     {         Method&lt;interface&gt;(); // Get compile error here!     } }   The error I get is "Type name expected, but local variable name found". If I try  ...     foreach(var interface in interfaces)     {         Method&lt;interface.MakeGenericType()&gt;(); // Still get compile error here!     } }   I get "Cannot apply operator '&lt;' to operands of type 'method group' and 'System.Type'" Any idea on how to get around this problem?
24043
I'm trying to work with  in Java.   I want to implement arithmetic functions.  For this, I will first require a way to normalize the functions.  I know I can't add 1/6 and 1/2 until I have a common denominator. I will have to add 1/6 and 3/6.  A naive approach would have me add 2/12 and 6/12 and then reduce.  How can I achieve a common denominator with the least performance penalty?  What algorithm is best for this?    Version 8 (thanks to ):     Improvements include:         the equals() method is now consistent with the compareTo() method      final class Fraction extends Number {     private int numerator;     private int denominator;      public Fraction(int numerator, int denominator) {         if(denominator == 0) {             throw new IllegalArgumentException("denominator is zero");         }         if(denominator &lt; 0) {             numerator *= -1;             denominator *= -1;         }         this.numerator = numerator;         this.denominator = denominator;     }      public Fraction(int numerator) {         this.numerator = numerator;         this.denominator = 1;     }      public int getNumerator() {         return this.numerator;     }      public int getDenominator() {         return this.denominator;     }      public byte byteValue() {         return (byte) this.doubleValue();     }      public double doubleValue() {         return ((double) numerator)/((double) denominator);     }      public float floatValue() {         return (float) this.doubleValue();     }      public int intValue() {         return (int) this.doubleValue();     }      public long longValue() {         return (long) this.doubleValue();     }      public short shortValue() {         return (short) this.doubleValue();     }      public boolean equals(Fraction frac) {         return this.compareTo(frac) == 0;     }      public int compareTo(Fraction frac) {         long t = this.getNumerator() * frac.getDenominator();         long f = frac.getNumerator() * this.getDenominator();         int result = 0;         if(t&gt;f) {             result = 1;         }         else if(f&gt;t) {             result = -1;         }         return result;     } }     I have removed all previous versions.  My thanks to:
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?
92538
I'd like to create a Dictionary object, with string Keys, holding values which are of a generic type. I imagine that it would look something like this:  Dictionary&lt;string, List&lt;T&gt;&gt; d = new Dictionary&lt;string, List&lt;T&gt;&gt;();     And enable me to add the following:  d.Add("Numbers", new List&lt;int&gt;()); d.Add("Letters", new List&lt;string&gt;());   I know that I can do it for a list of strings, for example, using this syntax:  Dictionary&lt;string, List&lt;string&gt;&gt; d = new Dictionary&lt;string, List&lt;string&gt;&gt;(); d.Add("Key", new List&lt;string&gt;());   but I'd like to do it for a generic list if possible...  2 questions then:   Is it possible? What's the syntax?   Many thanks, Jon
124087
I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:  t =&gt; t.SomeProperty.Contains("stringValue");   So far I have got:      private static Expression.Lambda&lt;Func&lt;string, bool&gt;&gt; GetContainsExpression&lt;T&gt;(string propertyName, string propertyValue)     {         var parameterExp = Expression.Parameter(typeof(T), "type");         var propertyExp = Expression.Property(parameter, propertyName);         var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :)         ...         return Expression.Lambda&lt;Func&lt;string, bool&gt;&gt;(containsMethodExp, parameterExp); //then something like this     }   I just don't know how to reference the String.Contains() method.  Help appreciated.
1947
What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?  Consider the following sample code - inside the Example() method, what's the most concise way to invoke GenericMethod&lt;T&gt;() using the Type stored in the myType variable?  public class Sample {     public void Example(string typeName)     {         Type myType = FindType(typeName);          // What goes here to call GenericMethod&lt;T&gt;()?         GenericMethod&lt;myType&gt;(); // This doesn't work          // What changes to call StaticMethod&lt;T&gt;()?         Sample.StaticMethod&lt;myType&gt;(); // This also doesn't work     }      public void GenericMethod&lt;T&gt;()     {         // ...     }      public static void StaticMethod&lt;T&gt;()     {         //...     } }
4666
Whats wrong with the following c# code? Compiler reports this error:  Inconsistent accessibility: parameter type 'ClassLibrary1.Interface1' is less accessible than method 'ClassLibrary1.Class1.Class1(ClassLibrary1.Interface1)'  with the following code:  interface Interface1&lt;T&gt; {     bool IsDataValid();     /* Other interfaces */ }  public class Class1&lt;T&gt; {     public Interface1&lt;T&gt; interface1;      public Class1(Interface1&lt;T&gt; interface1)     {         this.interface1 = interface1;     }  }   I've since designed my code differently using inheritence to but if anyone could tell me what the above is wrong I'd greatly appreciate it.
111415
I have a Generic class like that :  public class Repository&lt;T&gt; {...}   And I need to instance that with a string ... Example :  string _sample = "TypeRepository"; var _rep = new Repository&lt;sample&gt;();   How can I do that? Is that even possible?  Thanks!
6902
Let's say I have a generic member in a class or method, like so: public class Foo&lt;T&gt; {     public List&lt;T&gt; Bar { get; set; }          public void Baz()     {         // get type of T     }    }  When I instantiate the class, the T becomes MyTypeObject1, so the class has a generic list property: List&lt;MyTypeObject1&gt;. The same applies to a generic method in a non-generic class: public class Foo {     public void Bar&lt;T&gt;()     {         var baz = new List&lt;T&gt;();                  // get type of T     } }  I would like to know what type of objects the list of my class contains. So what type of T does the list property called Bar or the local variable baz contain? I cannot do Bar[0].GetType(), because the list might contain zero elements. How can I do it?
120216
This is probably not possible, but I have this class:  public class Metadata&lt;DataType&gt; where DataType : struct {     private DataType mDataType; }   There's more to it, but let's keep it simple.  The generic type (DataType) is limited to value types by the where statement.  What I want to do is have a list of these Metadata objects of varying types (DataType).  Such as:  List&lt;Metadata&gt; metadataObjects; metadataObjects.Add(new Metadata&lt;int&gt;()); metadataObjects.Add(new Metadata&lt;bool&gt;()); metadataObjects.Add(new Metadata&lt;double&gt;());   Is this even possible?
123439
Ok, bear with me guys and girls as I'm learning.  Here's my question.  I can't figure out why I can't override a method from a parent class.  Here's the code from the base class (yes, I pilfered the java code from an OOP book and am trying to rewrite it in C#).  using System;  public class MoodyObject {     protected String getMood()     {         return "moody";     }      public void queryMood()     {         Console.WriteLine("I feel " + getMood() + " today!");     } }   and here are my other 2 objects that inherit the base class (MoodyObject):  using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace ConsoleApplication1 {     public class SadObject: MoodyObject     {         protected String getMood()         {             return "sad";         }          //specialization         public void cry()         {             Console.WriteLine("wah...boohoo");         }     } }   And:  using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace ConsoleApplication1 {     public class HappyObject: MoodyObject     {         protected String getMood()         {             return "happy";         }          public void laugh()         {             Console.WriteLine("hehehehehehe.");         }     } }   and here is my main:  using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace ConsoleApplication1 {     class Program     {         static void Main(string[] args)         {             MoodyObject moodyObject = new MoodyObject();             SadObject sadObject = new SadObject();             HappyObject happyObject = new HappyObject();              Console.WriteLine("How does the moody object feel today?");             moodyObject.queryMood();             Console.WriteLine("");             Console.WriteLine("How does the sad object feel today?");             sadObject.queryMood();             sadObject.cry();             Console.WriteLine("");             Console.WriteLine("How does the happy object feel today?");             happyObject.queryMood();             happyObject.laugh();         }     } }   As you can see, pretty basic stuff, but here's the output:     How does the moody object feel today?   I feel moody today!      How does the sad object feel today? I   feel moody today! wah...boohoo      How does the happy object feel today?   I feel moody today! hehehehehehe.   Press any key to continue . . .   Not as I expected.  I've tried to make the base method virtual and calling override when trying to override it and that just gets me this error "cannot override inherited member 'MoodyObject.getMood()' because it is not marked virtual, abstract, or override".  I also tried it without the virtual and override and it thinks I'm trying to hide the base method.  Again, I'm new to OOP and would appreciate any guidance.  EDITED TO ADD:  I found it!  The MoodyObject.cs was only a "solution item" in the solution explorer as opposed to a "ConsoleApplication1" item.  I dragged it down to where it belonged in the solution explorer and voila!  It works now.  I marked Luc's answer below as the answer because he offered the help I needed to get to where I have it resolved... I'm learning so much here.  It's amazing and you guys and girls are crazy smart!
50233
I have built myself a generic collection class which is defined like this.   public class StatisticItemHits&lt;T&gt;{...}   This class can be used with int and string values only. However this  public class StatisticItemHits&lt;T&gt; where T : string, int {...}   won't compile. What am I doing wrong?
112618
This causes a compile-time exception:  public sealed class ValidatesAttribute&lt;T&gt; : Attribute {  }  [Validates&lt;string&gt;] public static class StringValidation {  }   I realize C# does not support generic attributes. However, after much Googling, I can't seem to find the reason.  Does anyone know why generic types cannot derive from Attribute? Any theories?
14635
private string? typeOfContract {   get { return (string?)ViewState["typeOfContract"]; }   set { ViewState["typeOfContract"] = value; } }   Later in the code I use it like this:  typeOfContract = Request.QueryString["type"];   I am getting the following error at the declaration of typeOfContract line stating:     The type 'string' must be a non-nullable value type in order to use   it as parameter 'T' in the generic type or method   'System.Nullable&lt;T>'   Any ideas? Basically, I want to make sure that "type" exists in the QueryString before performing an action.
44272
EDIT:  I found out that I can get it to compile if I cast the IMetadataType object to the TMetadata type.  Why do I need to do this?  EDIT #2:  The "Values" property is a .NET dictionary of type &lt;TMetadata, TData&gt;.  I have this generic method:  private void FillMetadata&lt;TMetadata, TData&gt;     (Metadata&lt;TMetadata, TData&gt; oMetadata) where TMetadata : IMetadataType {     IMetadataType o;     oMetadata.Values.Add(o, (TData)(object)GetValue()); }   I have stripped the implementation to simplify it (I actually use a real object, not the IMetadataType declared here).  My question is, why doesn't this compile?  The compile error is on the Add() method:  "cannot convert from 'IMetadataType' to 'TMetadata'."  Isn't that what the "where" clause on the method is for?  What am I missing?
88076
This is what I've come up with as a method on a class inherited by many of my other classes. The idea is that it allows the simple comparison between properties of Objects of the same Type.  Now, this does work - but in the interest of improving the quality of my code I thought I'd throw it out for scrutiny. How can it be better/more efficient/etc.?  /// &lt;summary&gt; /// Compare property values (as strings) /// &lt;/summary&gt; /// &lt;param name="obj"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public bool PropertiesEqual(object comparisonObject) {      Type sourceType = this.GetType();     Type destinationType = comparisonObject.GetType();      if (sourceType == destinationType)     {         PropertyInfo[] sourceProperties = sourceType.GetProperties();         foreach (PropertyInfo pi in sourceProperties)         {             if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null &amp;&amp; destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))             {                 // if both are null, don't try to compare  (throws exception)             }             else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))             {                 // only need one property to be different to fail Equals.                 return false;             }         }     }     else     {         throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");     }      return true; }