Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting variable 'as type'

Tags:

c#

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?

like image 825
Mike Baxter Avatar asked Jan 14 '23 08:01

Mike Baxter


2 Answers

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

like image 173
Lloyd Avatar answered Jan 15 '23 21:01

Lloyd


Your query may be returning an object

service.Query(eventQuery)

so you are casting this object as your data type.

like image 20
Sachin Avatar answered Jan 15 '23 23:01

Sachin