Cast Exception when performing LINQ on IEnumerable - linq

Let's say I have two classes,
class A
{
}
class B : A
{
}
I have a method which accepts a parameter foo of type IEnumerable<A>;
void AMethod(IEnumerable<A> foo)
{
}
but instead pass in a value of type IEnumerable<B>.
AMethod(new[] { new B() });
This compiles and executes, though at execution foo has been implicitly cast to IEnumerable<B>. Now let's say my IEnumerable<B> contains objects of type A (I don't believe it matters whether they're mixed or all the same). When I call foo.Any() I get an exception:
Unable to cast object of type 'A' to type 'B'
I understand that I can't convert a base class to a subclass, but that's not what I'm trying to do (in fact at this point in execution, I don't even care what type it is). I guess LINQ is inherently trying to make this conversion, probably based on the fact that foo is type IEnumerable<B>. So, it seems as though I need to write two separate methods, one which handles IEnumerable<A> and one which handles IEnumerable<B>. I don't understand why I would need to do this. Any thoughts?
EDIT:
There's some dynamic casting and transformation going on that manages to spit out a IEnumerable<B> populated with 'A's, which until now I thought was impossible too. I'll do my best to translate what's happening leading up to this method call:
protected void SetDynamicData(dynamic data)
{
_data = data;
IsB = typeof(IBInterface).IsAssignableFrom(_data.DataType);
}
...
var foo = IsB ? _data.Cast<B>() : data.Cast<A>();
return BuildJqGridData<A, B, int>(gridModel, foo);

An IEnumerable<B> cannot contain objects of type A because and A is not a B.
I can write this code,
IEnumerable<B> dodgy = (new[] { new A() }).Cast<B>();
It will compile, despite being obviously wrong. The compiler assumes I know what I'm doing. Remember that no item in the IEnumerable sequence has yet been evaluated.
When I write code that evaluates a member of dodgy I get exception because an A is not a B and does not support casting to B.
I can write
IEnumerable<A> fine = new[] { new B() };
no cast is required and everything works fine because a B is an A.
If I do,
var hungrilyDodgy = (new[] { new A() }).Cast<B>().ToList();
the Tolist() will force enumeration and evaluation of the IEnumerable, therefore the exception will be thrown much sooner.

Related

When does c++ right value destruct in this scenario?

Here is the code:
class SomeType {
public:
SomeType() {}
~SomeType() {}
std::string xxx;
}
bool funtion_ab() {
SomeType(); // This is a right val;
// The right val destructs here when I test the code. I want to make sure that it would always destructs here.
int a = 0, b = 10;
....// other code
return true;
}
Please tell me if you know the truth. Thank you!
What you have is called a temporary object. From §6.7.7,
Temporary objects are created
when a prvalue is converted to an xvalue
or, more specifically,
[Note 3: Temporary objects are materialized:
...
when a prvalue that has type other than cv void appears as a discarded-value expression ([expr.context]).
— end note]
and, on the lifetime, the same section has this to say
Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created.
You can read more about the expression semantics, but in your case "full-expression" is fairly unambiguous.
SomeType();
The "full-expression" containing your constructor call is... the constructor call itself. So the destructor will be called immediately after evaluating the constructor. There are some exceptions to this rule (such as if the temporary object is thrown as an exception or is bound as a reference), but none of those apply here.
As noted in the comments, compilers are free to inline your constructor and destructor calls and then are free to notice that they do nothing and omit them entirely. Optimizers can do fun stuff with your code, provided it doesn't change the semantics. But a strict reading of the standard states that the destructor is called exactly where you suggested.

Adding value to generic collection in class not allowed because of scope

I'm having trouble adding elements to an object that keeps a collection of generic-typed values. I tried a Minimal Working Example that causes the error:
class OneElementQueue {
type eltType;
var elements : [0..0] eltType;
//initializer
proc init(type eltType) {
this.eltType = eltType;
}
proc add(element : eltType) {
this.elements[0] = element;
}
proc remove() : eltType {
return this.elements[0];
}
} //end of OneElementQueue
class Monkey {
var name: string;
var age: int;
proc init(name : string, age : int) {
this.name = name;
this.age = age;
}
} //end of class Monkey
var q = new owned OneElementQueue(Monkey);
var m = new owned Monkey("Kyle", 6);
q.add(m);
When I try to compile all of this, I get an error:
$ chpl BadQueue.chpl
BadQueue.chpl:12: In function 'add':
BadQueue.chpl:13: error: Scoped variable would outlive the value it is set to
BadQueue.chpl:12: note: consider scope of element
$
What is the correct way to go about adding something to a generic data structure like this? How am I going about this the wrong way?
There are two possible approaches you can take here, depending on what behavior you want:
"I want to have my collection take ownership of the Monkey objects"
In this case, you'll want to instantiate your OneElementQueue collection to store owned Monkey objects rather than simply [borrowed] Monkey objects, which is the default for class types. You can do this with the one line change (Try it Online):
var q = new owned OneElementQueue(owned Monkey);
In this approach, passing an owned Monkey to your add() method will pass the ownership to the argument and eventually to the collection, making the original object reference invalid (nil).
"I want to have my collection borrow the existing Monkey objects without taking ownership of them"
In this case, you'll need to tell the add() method that the argument passed into it will outlive the argument itself (and then be sure not to lie about it). In Chapel version 1.19, this can be done via lifetime annotations:
proc add(element : eltType) lifetime element > this {
where the annotation lifetime element > this asserts that the actual argument passed through element will outlive the this collection itself, so the compiler should not fear that the borrow will cease to exist once the formal argument has.
Lifetime annotations were not available in Chapel 1.18, so if you're using that version you need to use a slightly bigger hammer and apply pragma "unsafe" to the method. Note that pragmas are not an officially supported feature and may change in the future, so for this case, served as a stopgap until lifetime annotations had been implemented (Try it Online):
pragma "unsafe"
proc add(element : eltType) {

Why doesn't Typescript Intellisense show Object extensions?

Consider this code to extend the Object type:
interface Object
{
doSomething() : void;
}
Object.prototype.doSomething = function ()
{
//do something
}
With this in place, the following both compile:
(this as Object).doSomething();
this.doSomething();
BUT: when I'm typing the first line, Intellisense knows about the doSomething method and shows it in the auto-completion list. When I'm typing the second line, it does not.
I'm puzzled about this, because doesn't every variable derive from Object, and therefore why doesn't Visual Studio show the extra method in the method list?
Update:
Even though the Intellisense doesn't offer the method, it does seem to recognize it when I've typed it manually:
What could explain that?!
...because doesn't every variable derive from Object
No, for two reasons:
1. JavaScript (and TypeScript) has both objects and primitives. this can hold any value (in strict mode), and consequently can be a primitive:
"use strict";
foo();
foo.call(42);
function foo() {
console.log(typeof this);
}
Here's that same code in the TypeScript playground. In both cases (here and there), the above outputs:
undefined
number
...neither of which is derived from Object.
2. Not all objects inherit from Object.prototype:
var obj = Object.create(null);
console.log(typeof obj.toString); // undefined
console.log("toString" in obj); // false
If an object's prototype chain is rooted in an object that doesn't have a prototype at all (like obj above), it won't have the features of Object.prototype.
From your comment below:
I thought even primitives like number inherit from Object. If number doesn't, how does number.ToString() work?
Primitives are primitives, which don't inherit from Object. But you're right that most of them seem to, because number, string, boolean, and symbol have object counterparts (Number, String, Boolean, and Symbol) which do derive from Object. But not all primitives do: undefined and null throw a TypeError if you try to treat them like objects. (Yes, null is a primitive even though typeof null is "object".)
For the four of them that have object counterparts, when you use a primitive like an object like this:
var a = 42;
console.log(a.toString());
...an appropriate type of object is created and initialized from the primitive via the abstract ToObject operation in the spec, and the resulting object's method is called; then unless that method returns that object reference (I don't think any built-in method does, but you can add one that does), the temporary object is immediately eligible for garbage collection. (Naturally, JavaScript engines optimize this process in common cases like toString and valueOf.)
You can tell the object is temporary by doing something like this:
var a = 42;
console.log(a); // 42
console.log(typeof a); // "number"
a.foo = "bar"; // temp object created and released
console.log(a.foo); // undefined, the object wasn't assigned back to `a`
var b = new Number(42);
console.log(b); // (See below)
console.log(typeof b); // "object"
b.foo = "bar"; // since `b` refers to an object, the property...
console.log(b.foo); // ... is retained: "bar"
(Re "see below": In the Stack Snippets console, you see {} there; in Chrome's real console, what you see depends on whether you have the console open: If you don't, opening it later will show you 42; if you do, you'll see ▶ Number {[[PrimitiveValue]]: 42} which you can expand with the ▶.)
Does number implement its own toString method, having nothing to do with Object?
Yes, but that doesn't really matter re your point about primitives and their odd relationship with Object.
So to round up:
this may contain a primitive, and while some primitives can be treated like objects, not all can.
this may contain an object reference for an object that doesn't derive from Object (which is to say, doesn't have Object.prototype in its prototype chain).
JavaScript is a hard language for IntelliSense. :-)

Move constructor not getting called? (C++11)

In the following example, why doesn't the move constructor get called in the construction of 'copy' inside fun, even though the 'src' argument of 'fun' is explicitly a rvalue reference and is only used in that construction?
struct Toy {
int data;
Toy(): data(0)
{
log("Constructed");
}
Toy(Toy const& src): data(src.data)
{
log("Copy-constructed");
}
Toy(Toy&& src): data(src.data)
{
log("Move-constructed");
}
};
Toy fun(Toy&& src)
{
Toy copy(src);
copy.data = 777;
return copy;
}
Toy toy(fun(Toy())); // LOG: Constructed Copy-constructed
While Bob && b is an rvalue reference, all named use of data after construction is using it as an lvalue.
So Bob&& b will only bind to rvalues, but when you use it it will not move.
The only ways to get an rvalue reference are:
A value without a name, such as a temporary return value or result of a cast.
Use of a local value variable in a simple return x; statement.
Explicitly casting to an rvalue, such as with std::move or std::forward.
This prevents data from being silently moved from on one line and then used on the next. It can help to think of rvalue as being 'I the programmer say this is not needed after this expression' at use, and 'only take things that are not needed afterwards' in function parameters. The temporary/return exceptions above are two spots the compiler can relatively safely guarantee this itself.
Finally, note that universal references (auto&& and T&&) look like rvalue references but sometimes are not.

creating an instance of another object in javascript

I want to know whether this sentence is correct?
You can do:
var a = new A();
if and only if A is instanceof Function.
Simply you can create an instance of function and you know a function is an object. Why can't we create an instance of other user-defined objects? Like this:
var b={};
var c = new b(); //error
EDIT: How can I change b so that I can create an instance of that?
You can actually use Object.create() to have some sugar around ECMAscript's prototypal nature. Like
var b = { };
var c = Object.create( b );
Now, c will have b on its prototype chain. ECMAscript or more precisely, prototypal inheritance doesn't work exactly the same way as a "classical inheritance". By calling new when invoking a function, you actually receiving a newly created object aswell. You can modify and access that object via the this value within that such called constructor function.
However, you didn't inherit anything so far. You would need to create and fill the .prototype - object for your constructor function before you create instances of it. This pattern annoyed lots of people, so ES5 brought as a more convinient way to directly inherit from other objects using Object.create().
Simply you can create an instance of function and you know a function is an object. Why can't we create an instance of other user-defined objects?
It’s not quite correct to say “you can create an instance of function”. The new keyword is a bit misleading - it makes JavaScript look like it implements object-orientation using classes, when in fact it doesn’t.
What you’re actually doing with new A() is creating an object using the constructor function A. The new keyword tells the JavaScript interpreter to return an object from A - specifically the object referred to as this inside of A.
EDIT: How can I change b so that I can create an instance of that?
In your example, b is an object (var b={};). If you change b into a constructor function, then you can create objects using it. (By convention, constructor functions in JavaScript start with capital letters.)
So:
function B () {
}
var c = new B();
You can add things to the prototype object of B, and they’ll be accessible on c too (and on any other objects you create using B):
function B () {
}
B.prototype.NAME = 'B';
B.prototype.hello = function () {
alert('Hello!');
}
var c = new B();
c.NAME // 'B'
c.hello() // alerts 'Hello!'
Short answer: The new operator requires its operand to have a special internal method [[Construct]] that generic objects do not have.
Long answer:
11.2.2 The new Operator
The production NewExpression : new NewExpression is evaluated as follows:
1. Evaluate NewExpression.
2. Call GetValue(Result(1)).
3. If Type(Result(2)) is not Object, throw a TypeError exception.
4. If Result(2) does not implement the internal [[Construct]] method, throw a TypeError exception.
5. Call the [[Construct]] method on Result(2), providing no arguments (that is, an empty list of arguments).
6. Return Result(5).
The production MemberExpression : new MemberExpression Arguments is evaluated as follows:
1. Evaluate MemberExpression.
2. Call GetValue(Result(1)).
3. Evaluate Arguments, producing an internal list of argument values (11.2.4).
4. If Type(Result(2)) is not Object, throw a TypeError exception.
5. If Result(2) does not implement the internal [[Construct]] method, throw a TypeError exception.
6. Call the [[Construct]] method on Result(2), providing the list Result(3) as the argument values.
7. Return Result(6).
You can also do
var b = new a.constructor();

Resources