Question

My Code:

public class Contact
{
    public string id{ get; set; }
    public string contact_type_id { get; set; }
    public string value{ get; set; }
    public string person_id { get; set; }
    public Contact()
    {

    }
}

public class Contact:Base.Contact
{
    public ContactType ContactType { get; set; }
    public Person Person {get; set;}
    public Contact()
    {
        ContactType = new ContactType();
        Person = new Person();
    }
}

And:

Contact c = new Contact();
Base.Contact cb = (Base.Contact)c;

The Problem:

The **cb** is set to **Contac** and not to **Base.Contact**.
Have any trick to do that????
Was it helpful?

Solution

I read the answers and still do not understand the problem! What is the problem with the above code?


Besides, from the comments, I understand that you need to serialize the base class only. I think there is no problem, to begin with. Look at the example-

class A
{
    public int a = -1;
};

class B : A
{
    public int b = 0;
};

class Program
{
    static void Main(string[] args)
    {
        A aobj = new B();
        aobj.a = 100; // <--- your aobj obviously cannot access B's members.
        Console.In.ReadLine();
    }
}

Now, if you must make your serialize function virtual, then yes, there is problem. Then this might help -

abstract class Ia
{
    public abstract void Serialize();
}
class A : Ia
{
    public int a = -1;
    sealed public override void Serialize() {
        Console.Out.WriteLine("In A serialize");
    }
};

class B : A
{
    public int b = 0;
    /*
     * Error here -
    public override void Serialize()
    {
        Console.Out.WriteLine("In B serialize");
    }
     */

    //this is ok. This can only be invoked by B's objects.
    public new void Serialize()
    {
        Console.Out.WriteLine("In B serialize");
    }
};

class Program
{
    static void Main(string[] args)
    {
        A aobj = new B();
        aobj.Serialize();
        Console.In.ReadLine();
    }
}

//Output: In A serialize

OTHER TIPS

Nothing to do with Silverlight.

That is what casting does -- you're still returning a reference to c, which is a Base.Contact.

You can't call ContactType or Person on cb (unless you upcast, which you shouldn't).

What is the problem with that?

You definitely can't turn a class into one of its base classes by casting. Depending on the type of serialization you're using, you may be able to tell the serializer to assume the class is of the base type, which would limit the serialization to the base type's members.

Add a copy constructor into a base class (e.g. public Contact(Contact other)) and then you can do this:

Contact c = new Contact();
Base.Contact cb = new Base.Contact(c);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top