Forum
 
ForumForumDiscussions and...Discussions and....Net framework ....Net framework ...How To: Reduce the pain of casting How To: Reduce the pain of casting
Previous Previous
 
Next Next
New Post
 04/02/2009 06:38
 
 Modified By RichardHowells  on 04/02/2009 12:43:06

I often find the cast syntax an annoyance. Because of the high precedence of the operator it forces extra parentheses and it also breaks the 'natural' left to right reading sequence of an expression. Here is an example for the case where a method returns a base type, but you need to use it as a derived type.

((Derived) (object.Method())).DerivedMethod

Whilst I am sure it's not a complete replacement for a cast, I've been experimenting with an extension method to achieve the same thing.  Here's the code for the extension method.  I happen to be working in code with a type called Element.  I wasn't quite brave enough to put the parameter type as object but I'd expect it to work.

        static public  T Cast<T>(this Element e) where T : Element
        {
            return (T)e;
        }

 

and here is the example above reworked to use it.

object.Method().Cast<Derived>().DerivedMethod()

 

What do people think?  It seems to me to conform better to the 'I want to read this statement left to right' school of thought.


Cheers,
- Richard
If this post helped you over a problem, or taught you something new, please login and rate it. Ratings are in the drop down in the top left corner
Previous Previous
 
Next Next
ForumForumDiscussions and...Discussions and....Net framework ....Net framework ...How To: Reduce the pain of casting How To: Reduce the pain of casting

Forum Usage Guidelines

The forums are a place for all to exchange ideas and techniques, and to post and answer questions.  All are welcome to read, registration is required to post. 

If you learn somthing new, discover or acquire a new technique, then please take a moment to register and rate the post that just helped you.  This site does not send spam and it does not release your personal details.  Full details in the site privacy policy.

We have some simple posting guidelines to keep the forums a pleasant and informative environment.

  • No flames, no trolls
  • No profanity, no racism
  • Site management has the final word on approving or removing any thread, post, or comment
  • English language only please

 

Copyright 2002-15 by Dynamisys Ltd