Reputation: 7258
Came across this snippet of code today:
EventFeed feed = null;
feed = service.Query(eventQuery) as EventFeed;
Why the as EventFeed
at the end? The return type of that function is already an EventFeed
, so I'm struggling to see the benefit of such a statement.
I found it difficult to search for this problem so I'm asking on here. What are the advantages to writing a line like this?
Upvotes: 4
Views: 122
Reputation: 1908
According your edit, if service.Query already returns an 'EventFeed', recasting it as such does nothing. Looks like duplicate code.
Upvotes: 0
Reputation: 152511
If the method signature for Query
specifies that it returns an EventFeed
(as opposed to returning a base class but you KNOW it's an EventFeed
). then the as
is unnecessary.
Just because you declare feed
as an EventFeed
doesn't mean that the object you get back from Query
is. You may be trying to put a square peg in a round hole.
Upvotes: 0
Reputation: 19646
It depends on the DataType returned from the Query
call. as
in this case will attempt to cast the result to the EventFeed
type, otherwise return null
.
Upvotes: 1
Reputation: 40970
Your query may be returning an object
service.Query(eventQuery)
so you are casting this object as your data type.
Upvotes: 1
Reputation: 29668
feed
might be declared as EventFeed
however the result of service.Query(eventQuery)
may not be.
Using as
stops an exception from being thrown and you end up with null
instead if the result of the expression cannot be cast as EventFeed
.
You can read more about as
here - http://msdn.microsoft.com/en-us/library/cscsdfbt(v=vs.71).aspx
Upvotes: 7