[DataContract]
public class SearchCriteria
{
[DataMember]
public string CountryID { get; set; }
}
[DataContract]
public class CitySearchCriteria: SearchCriteria
{
[DataMember]
public string CityID { get; set; }
}
I am creating an instance of SearchCriteria in my MVC controller action, and trying to convert it into CitySearchCriteria.
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.CountryID = "1";
CitySearchCriteria citySearchCriteria = searchCriteria as CitySearchCriteria;
The "citySearchCriteria" object after the above statement is showing NULL value. I was expecting it to show both properties, CountryID and CityID with CountryID populated, and CityID blank... but it is setting the object to NULL.
What could be the solution here? Has DataContract to do anything with this?
The comments are suggesting, you cannot convert a base to derive: but actually, I have done this successfully in my view, its just not working in controller action:
CitySearchCriteria citySearchCriteria = (CitySearchCriteria)Model.SearchCriteria;
This is converting successfully, so why not the similar thing working in controller action?
Everybody has already (and correctly) told you that you simply can't cast from Base to Derived, but it seems to me that you still don't get the reason why this line works in another chunk of your code:
CitySearchCriteria citySearchCriteria = (CitySearchCriteria)Model.SearchCriteria;
I think that you are a little bit confused about what the "Type" of an instance is. You didn't post the definition of Model, but I think that you have something like this:
public SearchCriteria SearchCriteria;
This doesn't mean that SearchCriteria always contains instances of SearchCriteria, but only that it contains instances of types that can be cast to SearchCriteria. In your case it can contain instances of SearchCriteria or of CitySearchCriteria. I suppose that somewhere in your code you will find something like:
Model.SearchCriteria = new CitySearchCriteria();
and this is what allows yor cast to be executed correctly. You can see that the instance is indeed a CitySearchCriteria (and not simply an instance of SearchCriteria) executing this code just before the cast:
MessageBox.Show(Model.SearchCriteria.GetType().FullName);
To understand better you could try to modify the value in SearchCriteria just before your working cast as shown below only to find out that the cast won't work anymore:
Model.SearchCriteria = new SearchCriteria();
MessageBox.Show(Model.SearchCriteria.GetType().FullName);
CitySearchCriteria citySearchCriteria = (CitySearchCriteria)Model.SearchCriteria;