Explanation for C# Language Specification: 6.2.4 Explicit reference conversions - definition

As I mentioned in this post, I faced a for me not understandable compiler behaviour.
The code:
IEnumerable<IList<MyClass>> myData = //...getMyData
foreach (MyClass o in myData){}
It compiles, but fails on runtime: InvalidCastException; for me it is obvious.
If I change the IList to List as following, it complains:
IEnumerable<List<MyClass>> myData = //...getMyData
foreach (MyClass o in myData){}
When instead of the class type I put var as following, intellisense recognizes the correct type:
IEnumerable<List<MyClass>> myData = //...getMyData
foreach (var o in myData){}
My first question was: Why doesn't the compiler complain? The answer was that the behaviour respects the C# Language definition. See chapter 6.2.4 Explicit reference conversions, page 116.
Read the 4th and 5th statement:
• From any interface-type S to any class-type T, provided T is not sealed or provided T implements S.
• From any interface-type S to any interface-type T, provided S is not derived from T.
For the second part of the first statement provided T implements S is clear, no doubts. But why might we cast an interface-type S to any class-type T if it is not derived or not implemented?
In which case/scenario with an non empty list would the code run without throwing an InvalidCastException?

Related

What's the meaning of this syntax: Organization<(Currency, Coupon?) -> Sustenance>()

I stumbled upon this seemingly obscure syntax in an article about type aliases.
In Intellij IDEA this code compiles fine:
class Currency
class Coupon
open class Organization<SustenanceT>
class Sustenance
class Restaurant : Organization<(Currency, Coupon?) -> Sustenance>()
Not knowing how the syntax is named, I couldn't find any information on Google since keywords like "<(" seem to be ignored. In the Kotlin documentation I didn't find this syntax on pages about generics. The only relevant search result there was this short section about C function pointers but it doesn't explain much;
What's the meaning of this syntax, and for what use cases can I apply it in my projects?
You are parsing the syntax incorrectly. <( is not a token. Let me add some whitespace:
Organization<
(Currency, Coupon?) -> Sustenance
>
(Currency, Coupon?) -> Sustenance is a type that represents a function which accepts a Currency and Coupon? as parameters, and returns a Sustenance.
This type is then used as the type parameter of Organisation, just like the String in List<String>. What this means exactly will depend on what Organisation's type parameter represents. From the article, it seems to mean "the thing that the organisation does", so all in all, the entire type represents
an organisation that converts currency and coupon to sustenance

Scala doobie fragment with generic type parameter

I am trying to abstract inserting objects of different types into sql tables of similar structure. Here's what I'm trying to do:
class TableAccess[A : Meta](table: String) {
def insert(key: String, a: A): ConnectionIO[Unit] = {
(fr"insert into " ++ Fragment.const(table) ++ fr" values ($key, $a);").update.run.map(_ => ())
}
}
But I get this compile error:
[error] diverging implicit expansion for type doobie.util.param.Param[A]
[error] starting with method fromMeta in object Param
[error] (fr"insert into " ++ Fragment.const(table) ++ fr" values ($key, $a);").update.run.map(_ => ())
All I can find in the documentation is:
doobie allows you to interpolate values of any type (and options
thereof) with an Meta instance, which includes...
But it seems that is not enough in this case; what's the right typeclass/imports/conversions I need?
I'll go ahead an answer my own question, almost a year later. I never fully understood what was happening, and I have since updated to a newer version of doobie, so I am not sure how relevant this is. But now the documentation contains this clue:
Note: it is important to understand that Meta exists only to introduce
Get/Put pairs into implicit scope. You should never demand Meta as
evidence in user code: instead demand Get, Put, or both.
def foo[A: Meta](...) // don't do this
def foo[A: Get: Put](...) // ok
And indeed, between that change and the new version, this now compiles just fine for me:
class TableAccess[A: Get: Put](table: String) {
When the compiler is resolving implicit its searches for one of a specific type in the current scope. Here it seems like his finding more than one in his tree search.
It's not a matter of a missing typeclass or imports, it's more like you have too many of them and the compiler cant figure the right one.
Try removing some implicit and see how that works or pass them explicitly.
One way I resolved this was to localize the type parameters (and their evidence) onto the method (on a static/companion object), and then it compiled.
Something like
object MinimalGood {
def good[A: Meta, B: Meta](a: A, b: B): Update0 =
sql"""$a $b""".update
}

CLI/C++ function overload

I am currently writing a wrapper for a native C++ class in CLI/C++. I am on a little GamePacket class at the moment. Consider the following class:
public ref class GamePacket
{
public:
GamePacket();
~GamePacket();
generic<typename T>
where T : System::ValueType
void Write(T value)
{
this->bw->Write(value);
}
};
I want that I'm able to call the function as following in C#, using my Wrapper:
Packet.Write<Int32>(1234);
Packet.Write<byte>(1);
However, I can't compile my wrapper. Error:
Error 1 error C2664: 'void System::IO::BinaryWriter::Write(System::String ^)' : cannot convert argument 1 from 'T' to 'bool'
I don't understand this error, where does the System::String^ comes from. I'm seeing a lot of overloads of the Write() method, does CLI/C++ not call the correct one, and if so, how can I make it call the correct one?
Reference MSDN: http://msdn.microsoft.com/en-us/library/system.io.binarywriter.write(v=vs.110).aspx
Templates and generics don't work the same.
With templates, the code gets recompiled for each set of parameters, and the results can be pretty different (different local variable types, different function overloads selected). Specialization makes this really powerful.
With generics, the code only gets compiled once, and the overload resolution is done without actually knowing the final parameters. So when you call Write(value), the only things the compiler knows is that
value can be converted to Object^, because everything can
value derives from ValueType, because your constraint tells it
Unfortunately, using just that information, the compiler can't find an overload of Write that can be used.
It seems like you expected it to use Write(bool) when T is bool, Write(int) when T is int, and so on. Templates would work like that. Generics don't.
Your options are:
a dozen different copies of your method, each of which has a fixed argument type that can be used to select the right overload of BinaryWrite::Write
find the overload yourself using reflection, make a delegate matching the right overload, and call it
use expression trees or the dynamic language runtime to find and make a delegate matching the right overload, and then you call it

I cannot understand how Dart Editor analyze source code

Dart Editor version 1.2.0.release (STABLE). Dart SDK version 1.2.0.
This source code produces runtime exception.
void main() {
test(new Base());
}
void test(Child child) {
}
class Base {
}
class Child extends Base {
}
I assumed that the analyzer generates something like this.
The argument type 'Base' cannot be assigned to the parameter type 'Child'
But I can only detect this error at runtime when occurred this exception (post factum).
Unhandled exception:
type 'Base' is not a subtype of type 'Child' of 'child'.
The analyzer is following the language specification here.
It only warns if a the static type of the argument expression is not assignable to the type of function the parameter.
In Dart, expressions of one type is assignable to variables of another type if either type is a subtype of the other.
That is not a safe type check. It does not find all possible errors. On the other hand, it also does not disallow some correct uses like:
Base foo = new Child();
void action(Child c) { ... }
action(foo); // Perfectly correct code at runtime.
Other languages have safe assignment checks, but they also prevent some correct programs. You then have to add (unsafe/runtime checked) cast operators to tell the compiler that you know the program is safe. It's a trade-off where Dart has chosen to be permissive and avoid most casts.
Let's try to be polite and answer the question without any prejudice.
I think I understand what you expected and here my angle on what the error means:
You are invoking the method with the argument of type Base
The method is expecting an argument of type Child
The Child is not equal to the Base, neither is a subtype of it (as a fact it is the Child that is a subtype of the Base)
It is working as expected as it makes only sense to provide object of the expected type (or it's subtypes - specialisations).
Update:
After reading again your question I realised that you are pointing out that editor is not finding the type problem. I assume this is due to the point that Dart programs are dynamic and hence certain checks are not done before the runtime.
Hope it helps ;-)

Lambdas with captured variables

Consider the following line of code:
private void DoThis() {
int i = 5;
var repo = new ReportsRepository<RptCriteriaHint>();
// This does NOT work
var query1 = repo.Find(x => x.CriteriaTypeID == i).ToList<RptCriteriaHint>();
// This DOES work
var query1 = repo.Find(x => x.CriteriaTypeID == 5).ToList<RptCriteriaHint>();
}
So when I hardwire an actual number into the lambda function, it works fine. When I use a captured variable into the expression it comes back with the following error:
No mapping exists from object type
ReportBuilder.Reporter+<>c__DisplayClass0
to a known managed provider native
type.
Why? How can I fix it?
Technically, the correct way to fix this is for the framework that is accepting the expression tree from your lambda to evaluate the i reference; in other words, it's a LINQ framework limitation for some specific framework. What it is currently trying to do is interpret the i as a member access on some type known to it (the provider) from the database. Because of the way lambda variable capture works, the i local variable is actually a field on a hidden class, the one with the funny name, that the provider doesn't recognize.
So, it's a framework problem.
If you really must get by, you could construct the expression manually, like this:
ParameterExpression x = Expression.Parameter(typeof(RptCriteriaHint), "x");
var query = repo.Find(
Expression.Lambda<Func<RptCriteriaHint,bool>>(
Expression.Equal(
Expression.MakeMemberAccess(
x,
typeof(RptCriteriaHint).GetProperty("CriteriaTypeID")),
Expression.Constant(i)),
x)).ToList();
... but that's just masochism.
Your comment on this entry prompts me to explain further.
Lambdas are convertible into one of two types: a delegate with the correct signature, or an Expression<TDelegate> of the correct signature. LINQ to external databases (as opposed to any kind of in-memory query) works using the second kind of conversion.
The compiler converts lambda expressions into expression trees, roughly speaking, by:
The syntax tree is parsed by the compiler - this happens for all code.
The syntax tree is rewritten after taking into account variable capture. Capturing variables is just like in a normal delegate or lambda - so display classes get created, and captured locals get moved into them (this is the same behaviour as variable capture in C# 2.0 anonymous delegates).
The new syntax tree is converted into a series of calls to the Expression class so that, at runtime, an object tree is created that faithfully represents the parsed text.
LINQ to external data sources is supposed to take this expression tree and interpret it for its semantic content, and interpret symbolic expressions inside the tree as either referring to things specific to its context (e.g. columns in the DB), or immediate values to convert. Usually, System.Reflection is used to look for framework-specific attributes to guide this conversion.
However, it looks like SubSonic is not properly treating symbolic references that it cannot find domain-specific correspondences for; rather than evaluating the symbolic references, it's just punting. Thus, it's a SubSonic problem.