Reputation: 17388
I have a class Base. A and B extend Base. There is also a class Relationship which contains two Base objects (source, target). Is it possible to determine whether source/target is an A or B instance?
Thanks.
Christian
PS:
Here is a little add on. I am using automapper and I would like to map the type of source/target to a string called 'Type' - GetType did not work (actually it works -s ee my comments - is and as are good solutions too):
Mapper.CreateMap<Item, ItemViewModel>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.ItemName == null ? "" : src.ItemName.Name))
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.GetType().ToString()));
How can I use is/as in this scenario?
Upvotes: 1
Views: 110
Reputation: 1499840
Yup:
if (source is A)
if (source is B)
etc
or:
A sourceA = source as A;
if (sourceA != null)
{
...
}
etc
See this question for more guidance - and there are plenty of other similar ones, too.
Upvotes: 8