I'm writing an ObjectHasValueConverter : IValueConverter for WPF.  The relevant function is Convert(object value, ...).  I want essentially want to do  return value != default(value.GetType())   Unfortunately, it seems default is a compile-time keyword and IValueConverter doesn't have a generic equivalent, so I can't just do default(T).  Obviously if value is an instance of a class or an array I can just check for null.  if (value.GetType().IsValueType | value.GetType().IsArray) {     return value != null; }   I have a special case for strings, returning !string.IsNullOrWhitespace(value).  For structs and other primitives, I'm hoping there's something cleaner than  if (value is int | value is short | value is long | ...) {     return (int)value != 0; }  if (value is float | value is double) {     return (double)value != 0; }  if (value is bool) {     return !(bool)value; } ...   I've scoured SO before writing this, but all the answers I found had to do with reflection and getting the members of a value type.  I didn't find anything relating to types that are put on the stack.
5349
I'm using reflection to loop through a Type's properties and set certain types to their default.  Now, I could do a switch on the type and set the default(Type) explicitly, but I'd rather do it in one line.  Is there a programmatic equivalent of default?
34848
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.  For instance:    System.out.println("obj: "+obj);   instead of:  System.out.println("obj: "+obj.toString());   Is there any difference apart from the null case? Can the latter case work, when the former does not?  Edit: What exactly is done, in case of the implicit call?
36534
Having recently introduced an overload of a method the application started to fail. Finally tracking it down, the new method is being called where I did not expect it to be.  We had  setValue( const std::wstring&amp; name, const std::wstring&amp; value );  std::wstring avalue( func() ); setValue( L"string", avalue ); std::wstring bvalue( func2() ? L"true", L"false" ); setValue( L"bool", bvalue ); setValue( L"empty", L"" );   It was changed so that when a bool value is stored we use the same strings (internal data storage of strings)  setValue( const std::wstring&amp; name, const std::wstring&amp; value ); setValue( const std::wstring&amp; name, const bool&amp; value );  std::wstring avalue( func() ); setValue( L"string", avalue ); setValue( L"bool", func2() ); setValue( L"empty", L"" ); &lt;&lt; --- this FAILS!?!   The problem with L"" is that it is implicitly casting and previously it was happy to be a std::wstring, but not it prefers to be a bool. The MSVC compiler does not complain, or raise warning, so I'm worried that even if I "fix" the setValue( L"empty", L"" ); to be  setValue( L"empty", std::wstring() );   somebody else may come later and simply use setValue( L"empty", L"" ); and have to track down this issue again.  We thought to use explicit on the method but it is not a valid keyword for this usage. Is there some way to get the compiler to complain about this, or otherwise prevent the issue?  Otherwise I'm thinking to change the name of the method which takes a bool to ensure it can't make an incorrect guess.
21733
EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)     ? null     : Convert.ToInt32(employeeNumberTextBox.Text),  I often find myself wanting to do things like this (EmployeeNumber is a Nullable&lt;int&gt; as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values).  Unfortunately, the compiler feels that  There is no implicit conversion between 'null' and 'int'  even though both types would be valid in an assignment operation to a nullable int on their own. Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the .Text string if it's not null. As far as I know the only way to do this is to use an if statement and/or assign it in two steps.  In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block... Does anyone know a more elegant solution?
3298
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?  For example I rather lazily used var in questionable circumstances, e.g.:-  foreach(var item in someList) { // ... } // Type of 'item' not clear. var something = someObject.SomeProperty; // Type of 'something' not clear. var something = someMethod(); // Type of 'something' not clear.   More legitimate uses of var are as follows:-  var l = new List&lt;string&gt;(); // Obvious what l will be. var s = new SomeClass(); // Obvious what s will be.   Interestingly LINQ seems to be a bit of a grey area, e.g.:-  var results = from r in dataContext.SomeTable               select r; // Not *entirely clear* what results will be here.   It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.  It's even worse when it comes to LINQ to objects, e.g.:-  var results = from item in someList               where item != 3               select item;   This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.  There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable&lt;int&gt; and IEnumerable&lt;double&gt; the caller might inadvertently pass in the wrong type.  var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
27078
I noticed for a while now the following syntax in some of our code:  if( NULL == var){    //... }   or  if( 0 == var){   //... }   and similar things.  Can someone please explain why did the person who wrote this choose this notation instead of the common var == 0 way)?  Is it a matter of style, or does it somehow affect performance?
3415
In .NET, a value type (C# struct) can't have a constructor with no parameters. According to  this is mandated by the CLI specification. What happens is that for every value-type a default constructor is created (by the compiler?) which initialized all members to zero (or null).  Why is it disallowed to define such a default constructor?  One trivial use is for rational numbers:  public struct Rational {     private long numerator;     private long denominator;      public Rational(long num, long denom)     { /* Todo: Find GCD etc. */ }      public Rational(long num)     {         numerator = num;         denominator = 1;     }      public Rational() // This is not allowed     {         numerator = 0;         denominator = 1;     } }   Using current version of C#, a default Rational is 0/0 which is not so cool.  PS: Will default parameters help solve this for C#&nbsp;4.0 or will the CLR-defined default constructor be called?     answered:     To use your example, what would you want to happen when someone did:   Rational[] fractions = new Rational[1000];       Should it run through your constructor 1000 times?   Sure it should, that's why I wrote the default constructor in the first place. The CLR should use the default zeroing constructor when no explicit default constructor is defined; that way you only pay for what you use. Then if I want a container of 1000 non-default Rationals (and want to optimize away the 1000 constructions) I will use a List&lt;Rational&gt; rather than an array.  This reason, in my mind, is not strong enough to prevent definition of a default constructor.
115421
In this simplified example I have a generic class, and a method that returns a Map regardless of the type parameter.  Why does the compiler wipe out the types on the map when I don't specify a type on the containing class?  import java.util.Map;  public class MyClass&lt;T&gt; {     public Map&lt;String, String&gt; getMap()     {            return null;     }      public void test()     {            MyClass&lt;Object&gt; success = new MyClass&lt;Object&gt;();         String s = success.getMap().get("");          MyClass unchecked = new MyClass();         Map&lt;String, String&gt; map = unchecked.getMap();  // Unchecked warning, why?         String s2 = map.get("");          MyClass fail = new MyClass();         String s3 = fail.getMap().get("");  // Compiler error, why?     } }   I get this compiler error.  MyClass.java:20: incompatible types found   : java.lang.Object required: java.lang.String                 String s3 = fail.getMap().get("");  // Compiler error
85842
Assuming the following hypothetical inheritance hierarchy:  public interface IA {   int ID { get; set; } }  public interface IB : IA {   string Name { get; set; } }   Using reflection and making the following call:   typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.Instance)    will only yield the properties of interface IB, which is "Name".   If we were to do a similar test on the following code,  public abstract class A {   public int ID { get; set; } }  public class B : A {   public string Name { get; set; } }   the call typeof(B).GetProperties(BindingFlags.Public | BindingFlags.Instance) will return an array of PropertyInfo objects for "ID" and "Name".  Is there an easy way to find all the properties in the inheritance hierarchy for interfaces as in the first example?
12175
Is it wrong to write:  class A { public:     virtual ~A() = 0; };   for an abstract base class?  At least that compiles in MSVC... Will it crash at run time?
105864
Say for a Point2 class, and the following Equals:  public override bool Equals ( object obj )  public bool Equals ( Point2 obj )   This is the one that is shown in the Effective C# 3:  public override bool Equals ( object obj ) {     // STEP 1: Check for null     if ( obj == null )     {         return false;     }      // STEP 3: equivalent data types     if ( this.GetType ( ) != obj.GetType ( ) )     {         return false;     }     return Equals ( ( Point2 ) obj ); }  public bool Equals ( Point2 obj ) {     // STEP 1: Check for null if nullable (e.g., a reference type)     if ( obj == null )     {         return false;     }     // STEP 2: Check for ReferenceEquals if this is a reference type     if ( ReferenceEquals ( this, obj ) )     {         return true;     }     // STEP 4: Possibly check for equivalent hash codes     if ( this.GetHashCode ( ) != obj.GetHashCode ( ) )     {         return false;     }     // STEP 5: Check base.Equals if base overrides Equals()     System.Diagnostics.Debug.Assert (         base.GetType ( ) != typeof ( object ) );      if ( !base.Equals ( obj ) )     {         return false;     }      // STEP 6: Compare identifying fields for equality.     return ( ( this.X.Equals ( obj.X ) ) &amp;&amp; ( this.Y.Equals ( obj.Y ) ) ); }
92147
typeof(int).Name   Will return System.Int32 does anyone know of a way to return "int"
30163
What is the difference between this:  void MyMethod(IMyInterface value) {     //... }   and this:  void MyMethod&lt;T&gt;(T value) where T : IMyInterface {     //... }
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?
115894
In C# are the nullable primitive types (i.e. bool?) just aliases for their corresponding Nullable&lt;T&gt; type or is there a difference between the two?
60345
C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance:  List&lt;int&gt; myInts = new List&lt;int&gt; {0,1,1,     2,3,5,8,13,21,34,55,89,144,233,377,     610,987,1597,2584,4181,6765};  //this statement is clunky List&lt;string&gt; myStrings = myInts.     Select&lt;int,string&gt;( i =&gt; i.ToString() ).     ToList&lt;string&gt;();  //the type is inferred from the lambda expression //the compiler knows that it's taking an int and  //returning a string List&lt;string&gt; myStrings = myInts.     Select( i =&gt; i.ToString() ).     ToList();   This is needed for anonymous types where you don't know what the type parameter would be (in intellisense it shows up as 'a) because it's added by the compiler.  Class-level type parameters don't let you do this:  //sample generic class public class GenericDemo&lt;T&gt;  {     public GenericDemo ( T value )      {         GenericTypedProperty = value;     }      public T GenericTypedProperty {get; set;} }  //why can't I do: int anIntValue = 4181; var item = new GenericDemo( anIntValue ); //type inference fails  //however I can create a wrapper like this: public static GenericDemo&lt;T&gt; Create&lt;T&gt; ( T value ) {     return new GenericDemo&lt;T&gt; ( value ); }  //then this works - type inference on the method compiles var item = Create( anIntValue );   Why doesn't C# support this class level generic type inference?
62588
Is it possible to get the Type of an Object (it's not an SObject)?  String s = 'test'; doSomething(s);  public static void doSomething(o Object) {     // need to find out if o is a string or an integer     type = IsThereAMethodToGetTheTypeOf(o) // ?     if(type='String') {         // do something for strings here ....     } else {         // do something else ....     } }   I think the Type class can't help me, because it has no way to get the type of an existing object instance, right? Any there any other way?  Since there is most likely no perfect solution possible within the current platform limitations, I posted an Idea on IdeaExchange here:   For SObject I have already this  public static string getType(SObject obj) {     if(obj==null) return '';     return obj.getSObjectType().getDescribe().getName()+''; }