Why Enumerable.Cast raises an InvalidCastException?
Well, you have incorrect expectations of Cast
, that's all - it's meant to deal with boxing/unboxing, reference and identity conversions, and that's all. It's unfortunate that the documentation isn't as clear as it might be :(
The solution is to use Select
:
doubleNumbers2 = intNumbers.Select(x => (double) x).ToArray();
Puzzling Enumerable.Cast InvalidCastException
That's very odd! There's a blog post here that describes how the behaviour of Cast<T>()
was changed between .NET 3.5 and .NET 3.5 SP1, but it still doesn't explain the InvalidCastException, which you even get if you rewrite your code thus:
var list = new[] { 1 };
var castedList = from long l in list select l;
Console.WriteLine(castedList.First());
Obviously you can work around it by doing the cast yourself
var castedList = list.Select(i => (long)i);
This works, but it doesn't explain the error in the first place. I tried casting the list to short and float and those threw the same exception.
Edit
That blog post does explain why it doesn't work!
Cast<T>()
is an extension method on IEnumerable
rather than IEnumerable<T>
. That means that by the time each value gets to the point where it's being cast, it has already been boxed back into a System.Object. In essence it's trying to do this:
int i = 1;
object o = i;
long l = (long)o;
This code throws the InvalidCastException you're getting. If you try to cast an int directly to a long you're fine, but casting a boxed int back to a long doesn't work.
Certainly an oddity!
Unexpected `Specified cast is not valid.` exception (Linq)
Enumerable.Cast
is implemented as an extension method on IEnumerable
(the non-generic interface).
This implication of this is that the values in the sequence are cast from object
, which means boxing and unboxing is involved for value types. You can only unbox to the exact type. For example:
int i = 1;
object boxed = i;
int unboxToInt = (int)boxed; // ok
uint unboxToUint = (uint)boxed; // invalid cast exception
You can read more about boxing in the documentation.
Casting to custom type, Enumerable.CastT and the as keyword
Even if it would have used the cast operator instead of as
it still wouldn't be invoking user defined explicit operators, so it wouldn't matter. The only difference would be the type of exception thrown.
Explicit operators aren't known at all by the runtime. According to the CLR there is no way to cast your search result to Item
. When the compiler notices that there is a cast that matches a given explicit operator it injects at compile time a call to that explicit operator (which is basically a static method) into the code. Once you get to runtime there is no remaining knowledge of the cast, there is simply a method call in place to handle the conversion.
Because this is how explicit operators are implemented, rather than providing knowledge to the runtime of how to do the conversion, there is no way for Cast
to inject the explicit operator's call into the code. It's already been compiled. When it was compiled there was no knowledge of any explicit operator to inject, so none was injected.
InvalidCastException trying to cast Object[] array to string array
You are getting this exception because in order to convert to array of strings, the elements themselves must be strings as well. You can do it with LINQ, though:
string[] winningNumber = al.Cast<object>().Select(o => o.ToString()).ToArray();
To deal with null
s, replace o.ToString()
with ""+o
or a conditional that checks for null
s.
Casting object to long
long id = Convert.ToInt64(dBlockTabellenOptionen.Id);
should do the trick.
C# App Grid Navigation - InvalidCastException
This is an invalid cast exception - in other words you are trying to use something that isn't of the type you expect. I noticed you are casting "ClickedItem" as both "SampleDataGroup" and as a "SampleDataItem". Unless there is some form of class inheritance going on here, this isn't possible. I would recommend you try the following code:
var group = e.ClickedItem as SampleDataGroup;
var groupId = group == null ? 0 : group.UniqueId;
var item = e.ClickedItem as SampleDataItem;
var itemId = item == null ? 0 : item.UniqueId;
I don't know if this is what you want but it will at least eliminate the error you are seeing. Hope that helps some!
EDIT & Another Issue:
I noticed that the next line after this error is:
// This won't work:
int intGroup = Convert.ToInt32(group);
This also doesn't look like it is going to work. I think you are going to want to learn more about strong types in .NET and how they work. Maybe the following MSDN page will get you started: http://msdn.microsoft.com/en-us/library/ms173104.aspx
Why cant Listdecimal be casted to Listint?
You need:
new List<decimal>() { 6m}.Select(d => (int)d).ToList<int>();
or
new List<decimal>() { 6m}.ConvertAll(d => (int)d);
use Select
with any IEnumerable
, ConvertAll
will only work with List
.Cast
should be used when you need to process members of (for example) an array list as if they were strongly typed.
thanks to @hvd for correcting me
Related Topics
Can a C# Lambda Expression Have More Than One Statement
Windows Forms Progressbar: Easiest Way to Start/Stop Marquee
Mono Https Webrequest Fails with "The Authentication or Decryption Has Failed"
Obtain Sha-256 String of a String
How to Get Little Endian Data from Big Endian in C# Using Bitconverter.Toint32 Method
Parsing a JSON File with .Net Core 3.0/System.Text.JSON
Get Ssid of the Wireless Network I am Connected to with C# .Net on Windows Vista
How to Implement a Progress Bar in C#
Exception When Addwithvalue Parameter Is Null
How to Delete a File Which Is Locked by Another Process in C#
Run Process as Administrator from a Non-Admin Application
How to Execute a Command in a Remote Computer
Updating an Observablecollection in a Separate Thread
Windows 7 and Vista Uac - Programmatically Requesting Elevation in C#
Attach Debugger in C# to Another Process
Capture Multiple Key Downs in C#
Use Reflection to Invoke an Overridden Base Method
How to Convert Datetime To/From Specific String Format (Both Ways, E.G. Given Format Is "Yyyymmdd")