Using the 'is' operator versus an abstract enum in identifying a child class.
I have a reference to a child class of some parent class. I am trying to identify this child class as the outcome of a function is determined by which child class it is. How should I approach this?
// Utilising the 'is' operator.
public abstract class Parent : MonoBehaviour
{
}
public class ChildA : Parent
{
}
public class ChildB : Parent
{
}
public class SomeOtherClass : MonoBehaviour
{
public void DoSomething(Parent p)
{
if (p is ChildA)
{
// Do something.
}
else if (p is ChildB)
{
// Do something else.
}
}
}
// Utilising an enum.
public enum Children { ChildA, ChildB }
public abstract class Parent : MonoBehaviour
{
public abstract Children Child { get; }
}
public class ChildA : Parent
{
public override Children Child { get { return Children.ChildA; } }
}
public class ChildB : Parent
{
public override Children Child { get { return Children.ChildB; } }
}
public class SomeOtherClass : MonoBehaviour
{
public void DoSomething(Parent p)
{
if (p.Child == Children.ChildA)
{
// Do something.
}
else if (p.Child == Children.ChildB)
{
// Do something else.
}
}
}
Will using one or the other induce significant overhead? Will using one or the other cause problems/inconveniences later down the line? Is one or the other bad coding practice? Or would you use an entirely different approach as opposed to the two examples above. Interfaces maybe?
To clarify, these checks will be made fairly frequently.
Your answer
Follow this Question
Related Questions
Using a subclass in the inspector in place of a parent class and accessing the subclass variables 1 Answer
Unity3d select random enum in another script 1 Answer
Create an array of scripts that don't affect each other? 1 Answer
How Do I Set A Parent Classes' Variables and override their functions 1 Answer
Can I set one enum value equal to another enum value? 2 Answers