views:

562

answers:

3

I have a Linq to SQL DataContext with SQL functions into it. While the retrieve object is good, I would like to add a property to the object and same time shortens the object name. So I made an object Reminder that inherits from the Linq to SQL object fnRTHU_ReminderByTaskResult with the property I wanted.

public class Reminder : fnRTHU_ReminderByTaskResult
{
    public string MyProperty {get;set;}
}

Then when the function is bind to the list I try in the aspx file to do:

<asp:Literal runat="server" Text='<%# ((Reminder)DataBinder.Container).MyProperty %>' />

Where DataBinder.Container is of type fnRTHU_ReminderByTaskResult. This results in an InvalidCastException, unable to cast object type fnRTHU_ReminderByTaskResult to type Reminder. I don't understand since I inherit from the type I'm casting from.

A: 

Unfortunately you are attempting to downcast which C# does not support. You are not able to cast from a parent type to a child type.

Andrew Hare
You definately can down cast a parent *reference* to a child reference as long as the underlying object is a child (or child of child).
JaredPar
That really has nothing to do with what I said. I said parent "type" not parent "reference".
Andrew Hare
@Andrew, your answer says C# does not support down casting which it does.
JaredPar
+1  A: 

The problem is your attempting to case an instance of a Base class to a Child class. This is not valid because Child inherits from Base. There is no guarantee that a case from Base to Child will work (this is known as a downcaste). Up casts (Child to Base) are safe.

This will work though if the Container property is an instance of Reminder. In this case, it does not appear to be.

JaredPar
Got two good answer, but the one I selected as a possible solution to be implemented hope you don't mind voted your answer up tho.
lucian.jp
@lucian.jp What!!!! Just kidding. don't mind a bit. Glad to help out.
JaredPar
+2  A: 

Since the Linq to Sql function returns that base class, your object was never that of your derived class. Therefore, when trying to cast down, it can't do it. You can however provide implicit and explicit casting implementations within your class that would allow this cast to work.

See here

BFree