Setting the variable as type

Found this piece of code today:

EventFeed feed = null; feed = service.Query(eventQuery) as EventFeed; 

Why as EventFeed at the end? The return type of this function is already EventFeed , so I try my best to see the advantage of such a statement.

It was hard for me to find this problem, so I ask here. What are the benefits of writing such a line?

+4
source share
5 answers

feed may be declared as EventFeed , however the result of service.Query(eventQuery) may not be the same.

Using as stops an exception from the created exception and as a result it turns out null if the result of the expression cannot be distinguished as EventFeed .

You can learn more about as here - http://msdn.microsoft.com/en-us/library/cscsdfbt(v=vs.71).aspx

+7
source

It depends on the DataType returned by the Query call. as in this case will try to pass the result to the EventFeed type, otherwise return null .

+1
source

object may be returned in your request

 service.Query(eventQuery) 

so that you select this object as your data type.

+1
source

If the method signature for Query indicates that it returns an EventFeed (as opposed to returning a base class, but you KNOW its EventFeed ). then as not required.

Just because you declare feed as an EventFeed does not mean that the object you are returning from Query is. You might be trying to fit a square pin into a round hole.

0
source

According to your changes, if service.Query already returns "EventFeed", processing it as such does nothing. Looks like duplicate code.

0
source

Source: https://habr.com/ru/post/1481970/


All Articles