Synopsis: | Use the correct way of casting |
Language: | C# |
Severity Level: | 7 |
Category: | Object oriented |
Description: |
If a type of an object is determined by design, then use explicit casting. If the type is unknown use the "as" operator and check against null to see if casting succeeded (see [7@608]). Avoid double casting by first checking the type with the "is" operator and then do the actual casting. This is only possible for reference types. Example: ISomeInterface y = null; if (x is ISomeInterface) // "is" operator uses a cast. { y = (ISomeInterface)x; // Here is the second cast. } // Better way if by design we know the type. ISomeInterface y = (ISomeInterface)x; // Or if we do not know the type use "as" ISomeInterface y = x as ISomeInterface; if (y != null) { // Use y. } |