Which do you think is better..
if (thing.GetType() == typeof(thisthing))
{
//do stuff for this type of thing.
}
Or give the objects an Enum property
if (thing.TypeName == NamesEnum.thisthing)
{
//do stuff for this type of thing.
}
Neither of these is a particularly extensible or maintainable approach.
It's typically better to design this directly into a virtual method in your type hierarchy, and just call the method. This allows other classes to override and provide custom functionality as appropriate.
In your case, the thisthing
type (which should be named ThisThing
if you want to follow .NET naming conventions) would just have a DoStuff
method which could be virtual if needed, and call it.
It depends:
if (thing.TypeName == NamesEnum.thisthing)
will run more performant then GetType()
as, this a simple comparison of 2 numeric values.
But:
if (thing.GetType() == typeof(thisthing))
is more more "flexible": when you do some refactoring, change type name or whatever, this condition will still work.
But will fail in condition, if 2 types belong to 2 different assemblies, instead in first case this still will be matched as equal,as you campare not types
but just enum values.
In short, there is no best approach, just most suitable for your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With