Under which circumstances would be (bool) mydata a valid cast when mydata type is System.Object?
I.e., obviously it would be a valid cast if the actual or unrderlying type is a boolean.
But would it be also a valid cast if the underlying type is int or maybe string? E.g.,
int value=1;
object mydata=value;
if ((bool) value) { ... }
Actually I am wondering how explicit conversions work in C#. Is some kind of reflection used to check if any valid conversion exists even when dealing with object types?
An int is not a bool. Try it and find out what happens (InvalidCastException).
One should note that most of the primitive types explicitly implement IConvertible, so you can get the cast you want this way:
int a = 37 ;
object b = a ;
bool c = (b as IConvertible) != null && (b as IConvertible).ToBoolean(null);
In the case of an int → bool conversion like this, the conversion is done in the usual C-like manner: zero is false and non-zero is true. Worth noting that this behaviour is at odds with formal logic wherein falsity is multi-valued, being all that is not true and truth uni-valued. But I digress.
As far as custom conversions go, whether implicit or explicit, all you're doing is providing custom methods that are recognized as operators by the compiler. The how of the conversion, of course, is up to you and your implementation. Here, the class Foo knows how to convert itself [explicitly] to an instance of class Bar:
class Foo
{
public static explicit operator Bar(Foo x)
{
// your implementation here
throw new NotImplementedException();
}
}
And here, class Bar knows how to [explicitly] convert itself to an int and to [implicitly] convert itself to a Foo:
class Bar
{
public static explicit operator int(Bar x)
{
// your implementation here
throw new NotImplementedException();
}
public static implicit operator Foo(Bar x)
{
// your implementation here
throw new NotImplementedException();
}
}
When you start mixing stuff up, the compiler will figure out what conversion method(s) are applicable (or not) and resolve them. You'll either get a compile error about the conversion or the compile will have selected a conversion method to be invoked at runtime.
At runtime, of course, it is possible that an exception might be thrown in the course of the conversion.
Paraphrased from Eric Lippert's blog:
http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx
The C# cast operator is used for identity preserving conversions (e.g. interpret this reference to base class as a reference to derived class) and identity destroying conversions (e.g. convert this int to a double). A single use of the cast operator is only allowed to invoke one of these.
Since you boxed an int, the only thing that the int may be unboxed to is int (this is an identity preserving case). Once it is unboxed to int, it may be converted (in the identity destroying case) to bool.
That is:
int iii = 123;
object ooo = iii; // Box the int
bool bbb = (bool) iii; // Perfectly legal
bool jjj = (bool) (int) ooo; // Perfectly legal
bool kkk = (bool) ooo; // Invalid cast exception
First thing first: a cast of an object to bool is valid only when the object is a reference type wrapper for the bool or Nullable<bool> type:
bool val1 = true;
object mydata1=val1;
if ((bool) val1) { ... } // This is valid
bool? val2 = false;
object mydata2=val2;
if ((bool) val2) { ... } // This is valid too
When you cast an object to another type in C#, the runtime has enough information about the runtime type of the object being typecast to validate the operation, and throw an InvalidCastException when the cast is invalid.
In situations when the dynamic type of the object at runtime does not match the type to which you would like it to cast, you should use methods of the Convert class.
Probably your best course of action to reduce exceptions and make casting easy is to use the as operator and a nullable boolean bool?.
object test1 = 1;
object test2 = true;
var testBool1 = test1 as bool?;
var testBool2 = test2 as bool?;
if (testBool1.HasValue)
{
// test1 is a boolean
bool mybool = testBool1.Value;
}
if (testBool2.HasValue)
{
// test2 is a boolean
bool mybool = testBool2.Value;
}
use this code for convert object to Boolean
var t = propInfo.GetValue(item, null);
bool state = Convert.ToBoolean(t);
use this code for convert object to Boolean
var t = propInfo.GetValue(item, null);
bool state = Convert.ToBoolean(t);
Related
I have a generic method defined like this:
public void MyMethod<T>(T myArgument)
The first thing I want to do is check if the value of myArgument is the default value for that type, something like this:
if (myArgument == default(T))
But this doesn't compile because I haven't guaranteed that T will implement the == operator. So I switched the code to this:
if (myArgument.Equals(default(T)))
Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for. I can add an explicit null check like this:
if (myArgument == null || myArgument.Equals(default(T)))
Now this feels redundant to me. ReSharper is even suggesting that I change the myArgument == null part into myArgument == default(T) which is where I started. Is there a better way to solve this problem?
I need to support both references types and value types.
To avoid boxing, the best way to compare generics for equality is with EqualityComparer<T>.Default. This respects IEquatable<T> (without boxing) as well as object.Equals, and handles all the Nullable<T> "lifted" nuances. Hence:
if(EqualityComparer<T>.Default.Equals(obj, default(T))) {
return obj;
}
This will match:
null for classes
null (empty) for Nullable<T>
zero/false/etc for other structs
How about this:
if (object.Equals(myArgument, default(T)))
{
//...
}
Using the static object.Equals() method avoids the need for you to do the null check yourself. Explicitly qualifying the call with object. probably isn't necessary depending on your context, but I normally prefix static calls with the type name just to make the code more soluble.
I was able to locate a Microsoft Connect article that discusses this issue in some detail:
Unfortunately, this behavior is by design and there is not an easy solution to enable use of with type parameters that may contain value types.
If the types are known to be reference types, the default overload of defined on object tests variables for reference equality, although a type may specify its own custom overload. The compiler determines which overload to use based on the static type of the variable (the determination is not polymorphic). Therefore, if you change your example to constrain the generic type parameter T to a non-sealed reference type (such as Exception), the compiler can determine the specific overload to use and the following code would compile:
public class Test<T> where T : Exception
If the types are known to be value types, performs specific value equality tests based on the exact types used. There is no good "default" comparison here since reference comparisons are not meaningful on value types and the compiler cannot know which specific value comparison to emit. The compiler could emit a call to ValueType.Equals(Object) but this method uses reflection and is quite inefficient compared to the specific value comparisons. Therefore, even if you were to specify a value-type constraint on T, there is nothing reasonable for the compiler to generate here:
public class Test<T> where T : struct
In the case you presented, where the compiler does not even know whether T is a value or reference type, there is similarly nothing to generate that would be valid for all possible types. A reference comparison would not be valid for value types and some sort of value comparison would be unexpected for reference types that do not overload.
Here is what you can do...
I have validated that both of these methods work for a generic comparison of reference and value types:
object.Equals(param, default(T))
or
EqualityComparer<T>.Default.Equals(param, default(T))
To do comparisons with the "==" operator you will need to use one of these methods:
If all cases of T derive from a known base class you can let the compiler know using generic type restrictions.
public void MyMethod<T>(T myArgument) where T : MyBase
The compiler then recognizes how to perform operations on MyBase and will not throw the "Operator '==' cannot be applied to operands of type 'T' and 'T'" error that you are seeing now.
Another option would be to restrict T to any type that implements IComparable.
public void MyMethod<T>(T myArgument) where T : IComparable
And then use the CompareTo method defined by the IComparable interface.
Try this:
if (EqualityComparer<T>.Default.Equals(myArgument, default(T)))
that should compile, and do what you want.
(Edited)
Marc Gravell has the best answer, but I wanted to post a simple code snippet I worked up to demonstrate it. Just run this in a simple C# console app:
public static class TypeHelper<T>
{
public static bool IsDefault(T val)
{
return EqualityComparer<T>.Default.Equals(obj,default(T));
}
}
static void Main(string[] args)
{
// value type
Console.WriteLine(TypeHelper<int>.IsDefault(1)); //False
Console.WriteLine(TypeHelper<int>.IsDefault(0)); // True
// reference type
Console.WriteLine(TypeHelper<string>.IsDefault("test")); //False
Console.WriteLine(TypeHelper<string>.IsDefault(null)); //True //True
Console.ReadKey();
}
One more thing: can someone with VS2008 try this as an extension method? I'm stuck with 2005 here and I'm curious to see if that would be allowed.
Edit: Here is how to get it working as an extension method:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// value type
Console.WriteLine(1.IsDefault());
Console.WriteLine(0.IsDefault());
// reference type
Console.WriteLine("test".IsDefault());
// null must be cast to a type
Console.WriteLine(((String)null).IsDefault());
}
}
// The type cannot be generic
public static class TypeHelper
{
// I made the method generic instead
public static bool IsDefault<T>(this T val)
{
return EqualityComparer<T>.Default.Equals(val, default(T));
}
}
To handle all types of T, including where T is a primitive type, you'll need to compile in both methods of comparison:
T Get<T>(Func<T> createObject)
{
T obj = createObject();
if (obj == null || obj.Equals(default(T)))
return obj;
// .. do a bunch of stuff
return obj;
}
Extension method based on accepted answer.
public static bool IsDefault<T>(this T inObj)
{
return EqualityComparer<T>.Default.Equals(inObj, default);
}
Usage:
private bool SomeMethod(){
var tValue = GetMyObject<MyObjectType>();
if (tValue == null || tValue.IsDefault()) return false;
}
Alternate with null to simplify:
public static bool IsNullOrDefault<T>(this T inObj)
{
if (inObj == null) return true;
return EqualityComparer<T>.Default.Equals(inObj, default);
}
Usage:
private bool SomeMethod(){
var tValue = GetMyObject<MyObjectType>();
if (tValue.IsNullOrDefault()) return false;
}
There is going to be a problem here -
If you're going to allow this to work for any type, default(T) will always be null for reference types, and 0 (or struct full of 0) for value types.
This is probably not the behavior you're after, though. If you want this to work in a generic way, you probably need to use reflection to check the type of T, and handle value types different than reference types.
Alternatively, you could put an interface constraint on this, and the interface could provide a way to check against the default of the class/struct.
I think you probably need to split this logic into two parts and check for null first.
public static bool IsNullOrEmpty<T>(T value)
{
if (IsNull(value))
{
return true;
}
if (value is string)
{
return string.IsNullOrEmpty(value as string);
}
return value.Equals(default(T));
}
public static bool IsNull<T>(T value)
{
if (value is ValueType)
{
return false;
}
return null == (object)value;
}
In the IsNull method, we're relying on the fact that ValueType objects can't be null by definition so if value happens to be a class which derives from ValueType, we already know it's not null. On the other hand, if it's not a value type then we can just compare value cast to an object against null. We could avoid the check against ValueType by going straight to a cast to object, but that would mean that a value type would get boxed which is something we probably want to avoid since it implies that a new object is created on the heap.
In the IsNullOrEmpty method, we're checking for the special case of a string. For all other types, we're comparing the value (which already know is not null) against it's default value which for all reference types is null and for value types is usually some form of zero (if they're integral).
Using these methods, the following code behaves as you might expect:
class Program
{
public class MyClass
{
public string MyString { get; set; }
}
static void Main()
{
int i1 = 1; Test("i1", i1); // False
int i2 = 0; Test("i2", i2); // True
int? i3 = 2; Test("i3", i3); // False
int? i4 = null; Test("i4", i4); // True
Console.WriteLine();
string s1 = "hello"; Test("s1", s1); // False
string s2 = null; Test("s2", s2); // True
string s3 = string.Empty; Test("s3", s3); // True
string s4 = ""; Test("s4", s4); // True
Console.WriteLine();
MyClass mc1 = new MyClass(); Test("mc1", mc1); // False
MyClass mc2 = null; Test("mc2", mc2); // True
}
public static void Test<T>(string fieldName, T field)
{
Console.WriteLine(fieldName + ": " + IsNullOrEmpty(field));
}
// public static bool IsNullOrEmpty<T>(T value) ...
// public static bool IsNull<T>(T value) ...
}
I use:
public class MyClass<T>
{
private bool IsNull()
{
var nullable = Nullable.GetUnderlyingType(typeof(T)) != null;
return nullable ? EqualityComparer<T>.Default.Equals(Value, default(T)) : false;
}
}
Just a hacky answer and as a reminder for myself.
But I find this quite helpful for my project.
The reason I write it like this is that because I don't want default integer 0 being marked as null if the value is 0
private static int o;
public static void Main()
{
//output: IsNull = False -> IsDefault = True
Console.WriteLine( "IsNull = " + IsNull( o ) + " -> IsDefault = " + IsDefault(o));
}
public static bool IsNull<T>(T paramValue)
{
if( string.IsNullOrEmpty(paramValue + "" ))
return true;
return false;
}
public static bool IsDefault<T>(T val)
{
return EqualityComparer<T>.Default.Equals(val, default(T));
}
Don't know if this works with your requirements or not, but you could constrain T to be a Type that implements an interface such as IComparable and then use the ComparesTo() method from that interface (which IIRC supports/handles nulls) like this:
public void MyMethod<T>(T myArgument) where T : IComparable
...
if (0 == myArgument.ComparesTo(default(T)))
There are probably other interfaces that you could use as well IEquitable, etc.
#ilitirit:
public class Class<T> where T : IComparable
{
public T Value { get; set; }
public void MyMethod(T val)
{
if (Value == val)
return;
}
}
Operator '==' cannot be applied to operands of type 'T' and 'T'
I can't think of a way to do this without the explicit null test followed by invoking the Equals method or object.Equals as suggested above.
You can devise a solution using System.Comparison but really that's going to end up with way more lines of code and increase complexity substantially.
I think you were close.
if (myArgument.Equals(default(T)))
Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for. I can add an explicit null check like this:
You just need to reverse the object on which the equals is being called for an elegant null-safe approach.
default(T).Equals(myArgument);
How can I implement a struct so that the following cast can be performed?
var a = new StatusedValue<double>(1, false);
var b = (StatusedValue<int>)a;
My implementation should behave similarly to Nullable<T>, which works fine. However, this code fails with System.InvalidCastException:
public struct StatusedValue<T> where T : struct
{
public StatusedValue(T value) : this(value, true)
{
}
public StatusedValue(T value, bool isValid)
{
this.value = value;
this.isValid = isValid;
}
private T value;
private bool isValid;
public static implicit operator StatusedValue<T>(T value)
{
return new StatusedValue<T>(value);
}
public static explicit operator T(StatusedValue<T> value)
{
return value.value;
}
}
Result:
Unable to cast object of type 'StatusedValue`1[System.Double]' to type
'StatusedValue`1[System.Int32]'.
This works for Nullable<T> types because they get special treatment from the compiler. This is called a "lifted conversion operator", and you cannot define your own.
From section 6.4.2 of the C# Specification:
6.4.2 Lifted conversion operators
Given a user-defined conversion operator that converts from a non-nullable value type S to a
non-nullable value type T, a lifted conversion operator exists that
converts from S? to T?. This lifted conversion operator performs an
unwrapping from S? to S followed by the user-defined conversion from S
to T followed by a wrapping from T to T?, except that a null valued
S? converts directly to a null valued T?. A lifted conversion operator
has the same implicit or explicit classification as its underlying
user-defined conversion operator. The term “user-defined conversion”
applies to the use of both user-defined and lifted conversion
operators
If you're happy calling a method, try
public StatusedValue<U> CastValue<U>() where U : struct
{
return new StatusedValue<U>((U)Convert.ChangeType(value, typeof(U)), isValid);
}
This will unfortunately throw at runtime rather than compile time if T cannot be converted to U.
Edit: As pointed out below, if you constrain to IConvertible as well as/instead of struct then every conversion is theoretically possible at compile time, and you'll only get a runtime failure because of bad runtime values.
Nullables are specially handled by the compiler, I don't know if this is the case here.
Your operators would allow this:
StatusedValue<int> b = (int)a;
which is probably not what you want, because IsValid is not copied this way.
You could implement an extension method like this:
public static StatusedValue<TTarget> Cast<TSource, TTarget>(this StatusedValue<TSource> source)
where TTarget : struct
where TSource : struct
{
return new StatusedValue<TTarget>(
(TTarget)Convert.ChangeType(
source.Value,
typeof(TTarget)),
source.IsValid);
}
b = a.Cast<int>();
But the compiler cannot check if the types are compatible. ChangeType also returns an object, thus boxing your value.
The answer to why it's like this has already been posted and marked as the answer.
However, you can simplify the syntax to make it easier and clearer to do this while retaining compile-time type-safety.
Firstly, write a helper class to avoid having to specify redundant type parameters:
public static class StatusedValue
{
public static StatusedValue<T> Create<T>(T value, bool isValid = true) where T: struct
{
return new StatusedValue<T>(value, isValid);
}
}
Next you need to expose the underlying value with a Value property (otherwise you can't cast it from code).
Finally you can change your original code from this:
var a = new StatusedValue<double>(1, false);
var b = (StatusedValue<int>)a;
To this:
var a = StatusedValue.Create(1.0, false);
var b = StatusedValue.Create((int)a.Value, false);
where you are doing a simple cast on a.Value.
For a workaround, you will need to provide a way for converting from one underlying type to the other, since the compiler won't be able to figure that out:
public StatusedValue<TResult> To<TResult>(Func<T, TResult> convertFunc)
where TResult : struct {
return new StatusedValue<TResult>(convertFunc(value), isValid);
}
You can then do:
var a = new StatusedValue<double>(1, false);
var b = a.To(Convert.ToInt32);
With some reflection you could build a lookup table of the Convert methods, and lookup the right one based on the type arguments, and then you could default the conversion function to null and if it's not provided, try to lookup the correct conversion automatically. This would remove the clumsy Convert.ToInt32 part, and simply do var b = a.To<int>();
As Rawling points out, Convert.ChangeType can be used. This would make my method look like:
public StatusedValue<T2> To<T2>(Func<T, T2> convertFunc = null)
where T2 : struct {
return new StatusedValue<T2>(
convertFunc == null
? (T2)Convert.ChangeType(value, typeof(T2))
: convertFunc(value),
isValid
);
}
If you don't need a casting, you can add a method like this:
public StatusedValue<int> ConvertToStatusedInt() {
return new StatusedValue<int>(Convert.ToInt32(value), isValid);
}
As suggested in comment:
public StatusedValue<Q> ConvertTo<Q>() where Q:struct {
return new StatusedValue<Q>((Q)Convert.ChangeType(value, typeof(Q)), isValid);
}
I have two types sourceType and targetType and I need to write a method in C#, which checks if values of sourceType can be assigned to a variable of targetType. The signature of the function is MatchResultTypeAndExpectedType(Type sourceType, Type targetType).
The inheritance is covered by IsAssignableFrom. In the case of convertible types I thought to use CanConvertFrom, but, for example, if both types are numerical, then it always returns false.
A test, which I performed:
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Decimal));
Console.WriteLine("Int16 to Decimal - " + typeConverter.CanConvertFrom(typeof(Int16)));
Console.WriteLine("UInt16 to Decimal - " + typeConverter.CanConvertFrom(typeof(UInt16)));
typeConverter = TypeDescriptor.GetConverter(typeof(long));
Console.WriteLine("UInt16 to Int64 - " + typeConverter.CanConvertFrom(typeof(uint)));
typeConverter = TypeDescriptor.GetConverter(typeof(Double));
Console.WriteLine("UInt16 to Double - " + typeConverter.CanConvertFrom(typeof(UInt16)));
typeConverter = TypeDescriptor.GetConverter(typeof(String));
Console.WriteLine("UInt16 to String - " + typeConverter.CanConvertFrom(typeof(UInt16)));
The result is:
Int16 to Decimal - False
UInt16 to Decimal - False
UInt16 to Int64 - False
UInt16 to Double - False
UInt16 to String - False
[EDIT] So my question:
Is there a way in .NET to check whether a value of a given type can be assigned to a variable of another type without knowing values, e.g., whether implicit conversion will succeed? More specific requirements for implementation of MatchResultTypeAndExpectedType(Type sourceType, Type targetType):
Source and target types are not known at compile time, since their assemblies are loaded later.
No values or objects can be provided as input.
No objects of the types can be created in the implementation, since it is not allowed by the rest of the system. Values of value types can be created.
Only implicit conversion has to be checked.
It is known whether sourceType is value type. So the signature of the method can be like MatchResultTypeAndExpectedType(Type sourceType, Boolean isSourceValueType, Type targetType)
One way is to implement Implicit Numeric Conversions Table, but it will not cover other conversions or user defined conversions.
The problem about implicit/explicit conversions is that they're resolved at compile time. So there is (as far as I know) no simple runtime check. However, the dynamic implementation will pick them out and invoke them at runtime. You can (however ugly) create a class which will attempt to perform the conversion, catch the exception if it fails, and report whether or not it passed:
public class TypeConverterChecker<TFrom, TTo>
{
public bool CanConvert { get; private set; }
public TypeConverterChecker(TFrom from)
{
try
{
TTo to = (TTo)(dynamic)from;
CanConvert = true;
}
catch
{
CanConvert = false;
}
}
}
Given some classes like:
public class Foo
{
public static implicit operator Bar(Foo foo)
{
return new Bar();
}
public static implicit operator Foo(Bar bar)
{
return new Foo();
}
}
public class Bar
{
}
public class Nope
{
}
Usage:
Console.WriteLine((new TypeConverterChecker<Foo, Bar>(new Foo())).CanConvert); //True
Console.WriteLine((new TypeConverterChecker<Bar, Foo>(new Bar())).CanConvert); //True
Console.WriteLine((new TypeConverterChecker<Foo, Nope>(new Foo())).CanConvert); //False
And with the types you tested:
Console.WriteLine((new TypeConverterChecker<Int16, Decimal>(0)).CanConvert); //True
Console.WriteLine((new TypeConverterChecker<UInt16, Decimal>(0)).CanConvert); //True
Console.WriteLine((new TypeConverterChecker<UInt16, Int64>(0)).CanConvert); //True
Console.WriteLine((new TypeConverterChecker<UInt16, Double>(0)).CanConvert); //True
Console.WriteLine((new TypeConverterChecker<UInt16, String>(0)).CanConvert); //False
Now I can imagine this can be modified to be more efficient (cache the result statically so subsequent lookups for the same TFrom, TTo combination don't have to attempt the conversion, for value-types ignore the need for an input instance to cast (just use default(TFrom)) and so on, but it should give you a start. It should be noted that you should not pass in null for TFrom from as all null conversions will pass (unless it's to a value-type)
You can also add a second try/catch to attempt using the Convert.ChangeType method and see if the types have defined IConvertable implementations that can be leveraged. (you may want to store this as a separate boolean flag so you know which type of conversion you need to perform later)
EDIT: If you don't know the types at compile time, you can take advantage of a bit of reflection to still leverage the conversion checker:
public static class TypeConverterChecker
{
public static bool Check(Type fromType, Type toType, object fromObject)
{
Type converterType = typeof(TypeConverterChecker<,>).MakeGenericType(fromType, toType);
object instance = Activator.CreateInstance(converterType, fromObject);
return (bool)converterType.GetProperty("CanConvert").GetGetMethod().Invoke(instance, null);
}
}
Your usage might be like:
object unknownObject = new Foo();
Type targetType = typeof(Bar);
Type sourceType = unknownObject.GetType();
Console.WriteLine(TypeConverterChecker.Check(sourceType, targetType, unknownObject));
targetType = typeof(Nope);
Console.WriteLine(TypeConverterChecker.Check(sourceType, targetType, unknownObject));
I implemented a solution, which partially satisfy my requirements. It is based on the answer from #ChrisSinclair, but does not require to provide an object of sourceType.
The implementation is:
public static Boolean MatchResultTypeAndExpectedType(Type sourceType, Type targetType) {
if (sourceType.IsValueType)
return Check(sourceType, targetType);
else
return targetType.IsAssignableFrom(sourceType);
}
public static bool Check(Type fromType, Type toType) {
Type converterType = typeof(TypeConverterChecker<,>).MakeGenericType(fromType, toType);
object instance = Activator.CreateInstance(converterType);
return (bool)converterType.GetProperty("CanConvert").GetGetMethod().Invoke(instance, null);
}
public class TypeConverterChecker<TFrom, TTo> {
public bool CanConvert { get; private set; }
public TypeConverterChecker() {
TFrom from = default(TFrom);
if (from == null)
if (typeof(TFrom).Equals(typeof(String)))
from = (TFrom)(dynamic)"";
else
from = (TFrom)Activator.CreateInstance(typeof(TFrom));
try {
TTo to = (dynamic)from;
CanConvert = true;
} catch {
CanConvert = false;
}
}
}
There are two problems with the solution:
It does not check if there are implicit conversions for non-value types (e.g., user defined). Since IsAssignableFrom is used, only inheritance is covered for non-value types.
It does not cover value types, which has null value as default and does not have default constructors, except String. String is explicitly covered.
You can always do this:
try
{
Convert.ChangeType(val, typeof(targetType));
return true;
}
catch (Exception)
{
return false;
}
I realize you don't have the instance, but you can easily and very cheaply create that with:
var val = Activator.CreateInstance(sourceType);
Note that Activator.CreateInstance() is extremely fast for value types.
Of course, for reference type just use Type.IsInstanceOfType().
Edit: I filed a bug report on microsoft connect::
https://connect.microsoft.com/VisualStudio/feedback/details/614234/delegate-createdelegate-allows-binding-functions-with-enum-parameters-to-the-enum-base-type#details
Consider the following thing:
public static Int32 Test(Int16 #short)
{
return #short;
}
and from calling code::
Func<Int16,Int32> test = Test; //valid method group conversion.
Func<Int16,StringComparison> test2 = Test; // doesn't compile, not valid method group conversion.
Func<Int16,StringComparison> test3 = test; // doesn't compile, invalid contra-variance.
Func<Int16,StringComparison> test4 = Delegate.CreateDelegate(typeof(Func<Int16,StringComparison>),test.Method) as Func<Int16,StringComparison>; // works fine.
Why can Delegate.CreateDelegate do this strange conversion that no other means of creating a function allows? Even worse, a somewhat more sensible conversion to say Int64 or Object both fail. I realize that StringComparison "extends" Int32, But I thought that was more of a compiler trick as enum's extend the Enum class.
Also, this conversion works for DynamicMethod.CreateDelegate, as well.
Edit just tried it with Nullable<Int32> it doesn't work, which is perplexing. I think the only "free" conversion is to Enum types to their underlying type, but why?
Note that this does not allow you to convert an int instance method (like GetHashCode) to an open method that takes the enum type, which is why I think this is a bug as the behavior is inconsistent.
Edit:
If we remove test2 and test3 line we can then test to see that the method,delegate, and the "illegal" delegate all work as expected.
Console.WriteLine(Test(0)); // prints 0
Console.WriteLine(test(0)); // prints 0
Console.WriteLine(test4(0)); //prints CurrentCulture
Edit:
Here is a very big abuse of this that I wrote in about 10 minutes. This creates an IEqualityComparer<T> for an TEnum, by basically grabbing the one for its an underlying type and then just wrapping the Equals, and HashCode and using this trick/abuse to convert the parameters to TEnums, rather than underlying type. If this is a bug I'd like to know so that I won't try to rely on this behavior.
class EnumComparer<TEnum> : EqualityComparer<TEnum> where TEnum : struct
{
static Func<TEnum, TEnum, bool> s_Equals;
static Func<TEnum, int> s_HashCode;
static EnumComparer<TEnum> s_default;
static EnumComparer()
{
if (!typeof(TEnum).IsEnum) throw new Exception("Not an enum type");
Type underlyingType = Enum.GetUnderlyingType(typeof(TEnum));
object equalityComparer = typeof(EqualityComparer<>).MakeGenericType(new[] { underlyingType }).GetProperty("Default").GetGetMethod().Invoke(null, null);
s_Equals = Delegate.CreateDelegate(typeof(Func<TEnum, TEnum, bool>), equalityComparer,equalityComparer.GetType().GetMethod("Equals", new[]{underlyingType,underlyingType})) as Func<TEnum,TEnum,bool>;
s_HashCode = Delegate.CreateDelegate(typeof(Func<TEnum, int>), equalityComparer, equalityComparer.GetType().GetMethod("GetHashCode", new[]{underlyingType})) as Func<TEnum, int>;
s_default = new EnumComparer<TEnum>();
}
public static new EnumComparer<TEnum> Default
{
get
{
return s_default;
}
}
public override bool Equals(TEnum x, TEnum y)
{
return s_Equals(x, y);
}
public override int GetHashCode(TEnum obj)
{
return s_HashCode(obj);
}
private EnumComparer()
{
}
}
This is not a bug. It is always possible to convert an integral value type to an enum like StringComparison. The compiler normally requires a cast but you are bypassing the compiler here. And just as in C#, there is no check to verify that the integral value actually represents one of the enumeration values.
I have a generic method defined like this:
public void MyMethod<T>(T myArgument)
The first thing I want to do is check if the value of myArgument is the default value for that type, something like this:
if (myArgument == default(T))
But this doesn't compile because I haven't guaranteed that T will implement the == operator. So I switched the code to this:
if (myArgument.Equals(default(T)))
Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for. I can add an explicit null check like this:
if (myArgument == null || myArgument.Equals(default(T)))
Now this feels redundant to me. ReSharper is even suggesting that I change the myArgument == null part into myArgument == default(T) which is where I started. Is there a better way to solve this problem?
I need to support both references types and value types.
To avoid boxing, the best way to compare generics for equality is with EqualityComparer<T>.Default. This respects IEquatable<T> (without boxing) as well as object.Equals, and handles all the Nullable<T> "lifted" nuances. Hence:
if(EqualityComparer<T>.Default.Equals(obj, default(T))) {
return obj;
}
This will match:
null for classes
null (empty) for Nullable<T>
zero/false/etc for other structs
How about this:
if (object.Equals(myArgument, default(T)))
{
//...
}
Using the static object.Equals() method avoids the need for you to do the null check yourself. Explicitly qualifying the call with object. probably isn't necessary depending on your context, but I normally prefix static calls with the type name just to make the code more soluble.
I was able to locate a Microsoft Connect article that discusses this issue in some detail:
Unfortunately, this behavior is by design and there is not an easy solution to enable use of with type parameters that may contain value types.
If the types are known to be reference types, the default overload of defined on object tests variables for reference equality, although a type may specify its own custom overload. The compiler determines which overload to use based on the static type of the variable (the determination is not polymorphic). Therefore, if you change your example to constrain the generic type parameter T to a non-sealed reference type (such as Exception), the compiler can determine the specific overload to use and the following code would compile:
public class Test<T> where T : Exception
If the types are known to be value types, performs specific value equality tests based on the exact types used. There is no good "default" comparison here since reference comparisons are not meaningful on value types and the compiler cannot know which specific value comparison to emit. The compiler could emit a call to ValueType.Equals(Object) but this method uses reflection and is quite inefficient compared to the specific value comparisons. Therefore, even if you were to specify a value-type constraint on T, there is nothing reasonable for the compiler to generate here:
public class Test<T> where T : struct
In the case you presented, where the compiler does not even know whether T is a value or reference type, there is similarly nothing to generate that would be valid for all possible types. A reference comparison would not be valid for value types and some sort of value comparison would be unexpected for reference types that do not overload.
Here is what you can do...
I have validated that both of these methods work for a generic comparison of reference and value types:
object.Equals(param, default(T))
or
EqualityComparer<T>.Default.Equals(param, default(T))
To do comparisons with the "==" operator you will need to use one of these methods:
If all cases of T derive from a known base class you can let the compiler know using generic type restrictions.
public void MyMethod<T>(T myArgument) where T : MyBase
The compiler then recognizes how to perform operations on MyBase and will not throw the "Operator '==' cannot be applied to operands of type 'T' and 'T'" error that you are seeing now.
Another option would be to restrict T to any type that implements IComparable.
public void MyMethod<T>(T myArgument) where T : IComparable
And then use the CompareTo method defined by the IComparable interface.
Try this:
if (EqualityComparer<T>.Default.Equals(myArgument, default(T)))
that should compile, and do what you want.
(Edited)
Marc Gravell has the best answer, but I wanted to post a simple code snippet I worked up to demonstrate it. Just run this in a simple C# console app:
public static class TypeHelper<T>
{
public static bool IsDefault(T val)
{
return EqualityComparer<T>.Default.Equals(obj,default(T));
}
}
static void Main(string[] args)
{
// value type
Console.WriteLine(TypeHelper<int>.IsDefault(1)); //False
Console.WriteLine(TypeHelper<int>.IsDefault(0)); // True
// reference type
Console.WriteLine(TypeHelper<string>.IsDefault("test")); //False
Console.WriteLine(TypeHelper<string>.IsDefault(null)); //True //True
Console.ReadKey();
}
One more thing: can someone with VS2008 try this as an extension method? I'm stuck with 2005 here and I'm curious to see if that would be allowed.
Edit: Here is how to get it working as an extension method:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// value type
Console.WriteLine(1.IsDefault());
Console.WriteLine(0.IsDefault());
// reference type
Console.WriteLine("test".IsDefault());
// null must be cast to a type
Console.WriteLine(((String)null).IsDefault());
}
}
// The type cannot be generic
public static class TypeHelper
{
// I made the method generic instead
public static bool IsDefault<T>(this T val)
{
return EqualityComparer<T>.Default.Equals(val, default(T));
}
}
To handle all types of T, including where T is a primitive type, you'll need to compile in both methods of comparison:
T Get<T>(Func<T> createObject)
{
T obj = createObject();
if (obj == null || obj.Equals(default(T)))
return obj;
// .. do a bunch of stuff
return obj;
}
Extension method based on accepted answer.
public static bool IsDefault<T>(this T inObj)
{
return EqualityComparer<T>.Default.Equals(inObj, default);
}
Usage:
private bool SomeMethod(){
var tValue = GetMyObject<MyObjectType>();
if (tValue == null || tValue.IsDefault()) return false;
}
Alternate with null to simplify:
public static bool IsNullOrDefault<T>(this T inObj)
{
if (inObj == null) return true;
return EqualityComparer<T>.Default.Equals(inObj, default);
}
Usage:
private bool SomeMethod(){
var tValue = GetMyObject<MyObjectType>();
if (tValue.IsNullOrDefault()) return false;
}
There is going to be a problem here -
If you're going to allow this to work for any type, default(T) will always be null for reference types, and 0 (or struct full of 0) for value types.
This is probably not the behavior you're after, though. If you want this to work in a generic way, you probably need to use reflection to check the type of T, and handle value types different than reference types.
Alternatively, you could put an interface constraint on this, and the interface could provide a way to check against the default of the class/struct.
I think you probably need to split this logic into two parts and check for null first.
public static bool IsNullOrEmpty<T>(T value)
{
if (IsNull(value))
{
return true;
}
if (value is string)
{
return string.IsNullOrEmpty(value as string);
}
return value.Equals(default(T));
}
public static bool IsNull<T>(T value)
{
if (value is ValueType)
{
return false;
}
return null == (object)value;
}
In the IsNull method, we're relying on the fact that ValueType objects can't be null by definition so if value happens to be a class which derives from ValueType, we already know it's not null. On the other hand, if it's not a value type then we can just compare value cast to an object against null. We could avoid the check against ValueType by going straight to a cast to object, but that would mean that a value type would get boxed which is something we probably want to avoid since it implies that a new object is created on the heap.
In the IsNullOrEmpty method, we're checking for the special case of a string. For all other types, we're comparing the value (which already know is not null) against it's default value which for all reference types is null and for value types is usually some form of zero (if they're integral).
Using these methods, the following code behaves as you might expect:
class Program
{
public class MyClass
{
public string MyString { get; set; }
}
static void Main()
{
int i1 = 1; Test("i1", i1); // False
int i2 = 0; Test("i2", i2); // True
int? i3 = 2; Test("i3", i3); // False
int? i4 = null; Test("i4", i4); // True
Console.WriteLine();
string s1 = "hello"; Test("s1", s1); // False
string s2 = null; Test("s2", s2); // True
string s3 = string.Empty; Test("s3", s3); // True
string s4 = ""; Test("s4", s4); // True
Console.WriteLine();
MyClass mc1 = new MyClass(); Test("mc1", mc1); // False
MyClass mc2 = null; Test("mc2", mc2); // True
}
public static void Test<T>(string fieldName, T field)
{
Console.WriteLine(fieldName + ": " + IsNullOrEmpty(field));
}
// public static bool IsNullOrEmpty<T>(T value) ...
// public static bool IsNull<T>(T value) ...
}
I use:
public class MyClass<T>
{
private bool IsNull()
{
var nullable = Nullable.GetUnderlyingType(typeof(T)) != null;
return nullable ? EqualityComparer<T>.Default.Equals(Value, default(T)) : false;
}
}
Just a hacky answer and as a reminder for myself.
But I find this quite helpful for my project.
The reason I write it like this is that because I don't want default integer 0 being marked as null if the value is 0
private static int o;
public static void Main()
{
//output: IsNull = False -> IsDefault = True
Console.WriteLine( "IsNull = " + IsNull( o ) + " -> IsDefault = " + IsDefault(o));
}
public static bool IsNull<T>(T paramValue)
{
if( string.IsNullOrEmpty(paramValue + "" ))
return true;
return false;
}
public static bool IsDefault<T>(T val)
{
return EqualityComparer<T>.Default.Equals(val, default(T));
}
Don't know if this works with your requirements or not, but you could constrain T to be a Type that implements an interface such as IComparable and then use the ComparesTo() method from that interface (which IIRC supports/handles nulls) like this:
public void MyMethod<T>(T myArgument) where T : IComparable
...
if (0 == myArgument.ComparesTo(default(T)))
There are probably other interfaces that you could use as well IEquitable, etc.
#ilitirit:
public class Class<T> where T : IComparable
{
public T Value { get; set; }
public void MyMethod(T val)
{
if (Value == val)
return;
}
}
Operator '==' cannot be applied to operands of type 'T' and 'T'
I can't think of a way to do this without the explicit null test followed by invoking the Equals method or object.Equals as suggested above.
You can devise a solution using System.Comparison but really that's going to end up with way more lines of code and increase complexity substantially.
I think you were close.
if (myArgument.Equals(default(T)))
Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for. I can add an explicit null check like this:
You just need to reverse the object on which the equals is being called for an elegant null-safe approach.
default(T).Equals(myArgument);