Get object type at runtime

I have the code below. I get an object whose type I do not know. I have to check three conditions to check its type, and then make the right choice.

Is there a way to get the type of an object at runtime and do a cast without checking any conditions?

The object that I have is a requirementTemplate , and I have to check it with many types to get its type, and then do the translation.

 if (requirementTemplate.GetType() == typeof(SRS_Requirement)) { ((SRS_Requirement)((TreeNodeInfo)ParentTreeNode.Tag).Handle).AssociatedFeature = ((SRS_Requirement)requirementTemplate).AssociatedFeature; } else if (requirementTemplate.GetType() == typeof(CRF_Requirement)) { ((CRF_Requirement)((TreeNodeInfo)ParentTreeNode.Tag).Handle).AssociatedFeature = customAttr.saveAttributesCustomList(AttributesCustomListCloned); } else if (requirementTemplate.GetType() == typeof(SAT_TestCase)) { ((SAT_TestCase)((TreeNodeInfo)ParentTreeNode.Tag).Handle).AssociatedFeature = ((SAT_TestCase)requirementTemplate).AssociatedFeature; } 
+4
source share
2 answers

I think you need to use the as keyword. Check how (C # link)

+3
source

the most appropriate answer here is either to implement a common interface, or to override a virtual method from a common base class, and use polymorphism to provide an implementation (from various implementation classes) at runtime. Then your method will look like this:

 (blah.Handle).AssociatedFeature = requirementTemplate.GetAssociatedFeature(); 

If the list is not exclusive (i.e. there are other implementations), then:

 var feature = requirementTemplate as IHasAssociatedFeature; if(feature != null) { (blah.Handle).AssociatedFeature = feature.GetAssociatedFeature(); } 

you can do similar things on the left side too, or convey this in context:

 var feature = requirementTemplate as IHasAssociatedFeature; if(feature != null) { feature.SetAssociatedFeature(blah); } 

(if necessary)


Another non-standard approach is switch on the listing here:

 switch(requirementTemplate.FeatureType) { case ... } 

One good thing about this is that it can be either specific to a specific or instance specific.

+2
source

All Articles