Reputation: 1411
I try to cast a variable type of Object int to a var.
My try is:
var dummy = (items[items.Count() - 1].GetType()) items[items.Count()-1];
I dunno what I'm doing wrong, i cant see my error, but the debugger says that only assign, decrement and "new Object"-expressions can be used as a command... But that's what I'm doing...
Can somebody show me my error? Many thanks in advance, and sorry for that "beginnerquestion".
Upvotes: 0
Views: 188
Reputation: 31184
Here's the source of the error you're experiencing.
Your compiler sees (items[items.Count() - 1].GetType())
as an expression, rather than a casting statement, so what it sees is
getAValue() (items[items.Count() - 1].GetType())
which doesn't make any sense.
you should cast your variable as others have said.
Upvotes: 1
Reputation: 19842
Casting is a compile type operation, you're telling the compiler: "This object is a [insert type here]". GetType()
is a runtime method that returns a specific type (the type Type
). So there are a couple of problems, you cannot use the runtime method in a compile time construct. Second, you would actually in this case be casting (assuming this was possible) to Type
rather than say String
(assuming GetType()
returned String
).
I'm not sure what you're trying to accomplish, but this is probably what you want to do: http://msdn.microsoft.com/en-us/library/dtb69x08.aspx
Also, I think you might not be understanding what var
is (based on some of your comments). You "cast things to var", var is essentially a shortcut which allows the compiler to infer the type. So something like this:
var myString = "this is a test";
Is the equivalent of:
string myString = "this is a test";
Upvotes: 1
Reputation: 148110
You need to use Convert.ChangeType
var obj = Convert.ChangeType(d, items[items.Count() - 1].GetType());
Upvotes: 2