1

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?

cs0815
  • 16,751
  • 45
  • 136
  • 299
  • Thanks I have played with GetType and this did not work. – cs0815 Oct 07 '10 at 12:39
  • Oops the GetType stuff I wrote actually works - there was a mistake at the frontend. Will accept Jon Skeet's answer though .... – cs0815 Oct 07 '10 at 12:47

3 Answers3

8

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.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    + 1 you beat me to it, do you have these answers cached or something? :) – Richard J. Ross III Oct 07 '10 at 12:36
  • Garr...you're too fast this morning (well, at least morning for me). – Justin Niessner Oct 07 '10 at 12:36
  • @Richard: Even better, it's quite clear if you've hung around SO for any length of time that Jon is actually a time traveller...and that he types *really* fast. – T.J. Crowder Oct 07 '10 at 12:37
  • Is this a code smell? Is there some way to avoid this problem entirely? – Chris Shouts Oct 07 '10 at 12:41
  • 1
    @Chris, maybe consider it to have a detectable odour, rather than being a strong smell. Problems solved by testing type are often better solved with inheritance (put something into base and override in both A and B), overriding (handle As and Bs as such rather than through their base, and hence have different behaviour when passed to the same method name) or generics (though note that C# generics don't allow the same sort of specialisation as C++ which is handy in some such cases). Detecting type does definitely have its place though. – Jon Hanna Oct 07 '10 at 12:58
4

yes.

if (source is B)...

Itay Karo
  • 17,924
  • 4
  • 40
  • 58
0

Using the is operator? :)

Philippe
  • 3,945
  • 3
  • 38
  • 56