I have read somewhere that,
A Derived class (or subclass) is an instance of its base class.
Given that, I am having problems with the following where I am inheriting a base class.
public class TransactionCategorisationRuleViewModel : CategorisationRuleViewModel
{
public long TransactionId { get; set; }
[Display(Name="Apply to All Transactions")]
public bool IsApplyAll { get; set; }
}
I also have a function with the following definition:
public CategorisationRuleViewModel GetNewRule()
{
// content
}
However, when I do this, I am getting an Error (Can not implicitly convert type CategorisationRuleViewModel to TransactionCategorisationRuleViewModel. )
TransactionCategorisationRuleViewModel vmRule = GetNewRule();
Let's take an easier example. We will have two classes:
class Animal { }
class Horse : Animal { }
And we are trying to call this method:
public Animal GetNewAnimal()
{
// content
}
So if we write:
Horse newHorse = GetNewAnimal();
It gives us a casting exception. This is because GetNewAnimal
returns an Animal. It might be a Horse, it might be a Pig. Since the compiler can't be sure, and you are doing implicit casting, it says "I know you want a Horse, but I can't be guaranteed that it will be, so I'm giving up."
The way you fix this is by doing explicit casting.
Horse newHorse = (Horse)GetNewAnimal();
This tells the compiler that the return type will be a Horse. However, if at runtime the return value cannot be casted as a Horse, the system will throw an InvalidCastException
.
So, to map to your example, take all the Horses and Animals in my post and replace with TransactionCategorisationRuleViewModel
, and CategorisationRuleViewModel
, respectively.
TransactionCategorisationRuleViewModel vmRule =
(TransactionCategorisationRuleViewModel)GetNewRule();
This will fix your exception, but you are taking the risk that GetNewRule
will actually return a TransactionCategorisationRuleViewModel
. It might be easier to return a TransactionCategorisationRuleViewModel
instead of the base class type.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments