C #,. Net, general programming architecture. GetType or Enum: which is better?

What do you think is better.

if (thing.GetType() == typeof(thisthing)) { //do stuff for this type of thing. } 

Or provide objects with an Enum property

  if (thing.TypeName == NamesEnum.thisthing) { //do stuff for this type of thing. } 
+4
source share
3 answers

It depends:

 if (thing.TypeName == NamesEnum.thisthing) 

will work faster than GetType() , as this is a simple comparison of two numeric values.

But:

 if (thing.GetType() == typeof(thisthing)) 

more "flexible": when you do some refactoring, change the type name or something else, this condition will work anyway.

But it will fail if 2 types belong to 2 different assemblies, instead, in the first case, it will match as equal, since you are not using types , but simply listing the values.

In short, there is no better approach best suited to your needs.

+3
source

None of these are particularly extensible or supported.

It is usually best to construct this directly in a virtual method in a type hierarchy and simply call the method. This allows other classes to override and provide the necessary functionality.

In your case, the thisthing type (which should be called thisthing if you want to follow the .NET naming conventions) will only have a DoStuff method, which can be virtual if necessary and call it.

+12
source

IF you work with base types that don't have subtypes ... your first example can be greatly shortened to

 if (thing is typeof(thisthing)) 

Depends on the situation. If you go to a lot of different types, you will need a switch statement at some point, so I would say option 2 if there are many types.

+3
source

Source: https://habr.com/ru/post/1480523/


All Articles