Casting objects in C# (ASP.Net MVC)

Posted by Mortanis on Stack Overflow See other posts from Stack Overflow or by Mortanis
Published on 2010-03-27T02:25:49Z Indexed on 2010/03/27 2:33 UTC
Read the original article Hit count: 238

Filed under:
|
|

I'm coming from a background in ColdFusion, and finally moving onto something modern, so please bear with me.

I'm running into a problem casting objects. I have two database tables that I'm using as Models - Residential and Commercial. Both of them share the majority of their fields, though each has a few unique fields. I've created another class as a container that contains the sum of all property fields. Query the Residential and Commercial, stuff it into my container, cunningly called Property. This works fine.

However, I'm having problems aliasing the fields from Residential/Commercial onto Property. It's quite easy to create a method for each property: fillPropertyByResidential(Residential source) and fillPropertyByCommercial(Commercial source), and alias the variables. That also works fine, but quite obviously will copy a bunch of code - all those fields that are shared between the two main Models.

So, I'd like a generic fillPropertyBySource() that takes the object, and detects if it's Residential or Commercial, fills the particular fields of each respective type, then do all the fields in common. Except, I gather in C# that variables created inside an If are only in the scope of the if, so I'm not sure how to do this.

    public property fillPropertyBySource(object source)
    {
        property prop = new property();
        if (source is Residential)
        {
            Residential o = (Residential)source;
            //Fill Residential only fields

        }
        else if (source is Commercial)
        {
            Commercial o = (Commercial)source;
            //Fill Commercial only fields
        }
        //Fill fields shared by both
        prop.price = (int)o.price;
        prop.bathrooms = (float)o.bathrooms;

        return prop;
    }

"o" being a Commercial or Residential only exists within the scope of the if. How do I detect the original type of the source object and take action?

Bear with me - the shift from ColdFusion into a modern language is pretty..... difficult. More so since I'm used to procedural code and MVC is a massive paradigm shift.

Edit: I should include the error: The name 'o' does not exist in the current context For the aliases of price and bathrooms in the shared area.

© Stack Overflow or respective owner

Related posts about c#

Related posts about objects