You cannot use this method!
If you do new , you create a new memory object of a certain size. In your case, new SearchCriteria() creates a new memory object with a sufficient size to hold one line, no more, no less.
In your last line, you do searchCriteria as CitySearchCriteria to apply the object in searchCriteria to the larger CitySearchCriteria type. But this is impossible. You are trying to "convert" a memory object that contains 1 line to a memory object that can contain 2 lines. But casting does not convert the new memory object. What will be the value of the new line? It just looks underwater to check if your searchCriteria link searchCriteria an object of type CitySearchCriteria . In your case: no (the object is of type searchCriteria ) and returns null .
So ... the following example WORKS (because CitySearchCriteria has already been created). This is also your solution:
SearchCriteria searchCriteria = new CitySearchCriteria(); CitySearchCriteria citySearchCriteria = searchCriteria as CitySearchCriteria;
And this does not work (since CitySearchCriteria has not yet been created). This is your situation:
SearchCriteria searchCriteria = new SearchCriteria(); CitySearchCriteria citySearchCriteria = searchCriteria as CitySearchCriteria;
This is the same as in the following example. This one works (since SearchCriteria has already been created):
object o = new SearchCriteria(); SearchCriteria searchCriteria = o as SearchCriteria;
And it does not (because SearchCriteria has not yet been created) ::
object o = new object(); SearchCriteria searchCriteria = o as SearchCriteria;
For the record: I would always use live translation, not a cast using as , unless you want to explicitly check if the object is of this type.
source share