Say, I want to check if a class is of a certain type, I could do it in the following way:
1: if (myClass.GetType().Equals(typeof(AnotherClass)))
2: {3: //do something
4: }It works fine, but I wouldn't call it "Clean Code", and is not very readable! As a developer it is very easy to end up with this code, because we think: "OK, I have to check if myClass is of a ceratin type, then I need to get its type and compare it to AnotherClass, but to find the type of AnotherClass I have to use the typeof functionality".
Back when I programmed Java I used the instanceof keyword, and this was actually how I rediscovered the is-keyword of C#. The same code segment as above, but using the is-keysword looks far more readable:
1: if (myClass is MyClass)
2: {3: //do something
4: }Even though the expression is not evaluated until run-time, you will get a compile-time warning if the expression is know to always be true or false, eg:
1: var myClass = new Int32();
2: if (myClass is Int32)
3: {4: //do something
5: }Even though it's a very obvious example, it demonstrates the compile time evaluation! The compiler shows me the following message:
Strive for clean code, and use is rather than GetType() whenever possible!The given expression is always of the provided ('int') type

0 kommentarer:
Post a Comment