My first Extension Method for Object
OK, I’m ashamed this extension method took me this long to think of. It is the first extension method that I’ve created that warrants extending Object as well. But the fact that it doesn’t exist makes me think there might be a reason for that as well (shrugs).
This method is a blood brother to FirstOrDefault. FirstOrDefault extends IEnumerable to return the first item in the list, or if there is nothing in the list, it returns the default value (often null).
This is CastOrDefault. It casts an object or returns the default value if it can’t.
Uses: in my current application I have to deal with a lot of lists that return base types (Component, object, Control, etc) and I need them more specific. So I end up writing the same block over and over to check if the object is null, if I can cast it, then cast the object, and return it. That code is now gone.
Here is a trivial example for when you know the name of object at runtime, but not at design time: