Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, .net, general programming architecture. GetType or Enum : Which is better? [closed]

Tags:

c#

.net

types

enums

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.
        }
like image 699
Guye Incognito Avatar asked Dec 02 '22 19:12

Guye Incognito


2 Answers

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.

like image 74
Reed Copsey Avatar answered Dec 04 '22 08:12

Reed Copsey


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.

like image 22
Tigran Avatar answered Dec 04 '22 08:12

Tigran