cs0815
cs0815

Reputation: 17388

Inheritance related question

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

Answers (3)

Philippe
Philippe

Reputation: 4051

Using the is operator? :)

Upvotes: 0

Itay Karo
Itay Karo

Reputation: 18286

yes.

if (source is B)...

Upvotes: 4

Jon Skeet
Jon Skeet

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

Related Questions