Why does a generic type constraint result in a no implicit reference conversion error?

Let’s simplify: interface IAnimal { … } interface ICage<T> where T : IAnimal { void Enclose(T animal); } class Tiger : IAnimal { … } class Fish : IAnimal { … } class Cage<T> : ICage<T> where T : IAnimal { … } ICage<IAnimal> cage = new Cage<Tiger>(); Your question is: why is the last … Read more

Multiple implicit conversions on custom types not allowed?

There is no multi-step user-defined implicit conversion. int -> bool -> A is allowed because the int->bool conversion isn’t user-defined. 12.3 Conversions [class.conv] 1 Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions and are used for implicit type conversions (clause 4), for initialization … Read more

Can we define implicit conversions of enums in c#?

There is a solution. Consider the following: public sealed class AccountStatus { public static readonly AccountStatus Open = new AccountStatus(1); public static readonly AccountStatus Closed = new AccountStatus(2); public static readonly SortedList<byte, AccountStatus> Values = new SortedList<byte, AccountStatus>(); private readonly byte Value; private AccountStatus(byte value) { this.Value = value; Values.Add(value, this); } public static implicit … Read more

Why does the Linq Cast helper not work with the implicit cast operator?

So why my explicit cast work, and the one inside .Cast<> doesn’t? Your explicit cast knows at compile time what the source and destination types are. The compiler can spot the explicit conversion, and emit code to invoke it. That isn’t the case with generic types. Note that this isn’t specific to Cast or LINQ … Read more

Is it guaranteed that new Integer(i) == i in Java?

Yes. JLS §5.6.2 specifies the rules for binary numeric promotion. In part: When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary: If any … Read more

Why does printf(“%f”,0); give undefined behavior?

The “%f” format requires an argument of type double. You’re giving it an argument of type int. That’s why the behavior is undefined. The standard does not guarantee that all-bits-zero is a valid representation of 0.0 (though it often is), or of any double value, or that int and double are the same size (remember … Read more

What is the meaning of “operator bool() const”

Member functions of the form operator TypeName() are conversion operators. They allow objects of the class type to be used as if they were of type TypeName and when they are, they are converted to TypeName using the conversion function. In this particular case, operator bool() allows an object of the class type to be … Read more