# Cleaner Cast Syntax

Is there any other way to do this without all the extra outside parens here?

((ScheduledTask)(scheduledTasks[intCount])).TaskIntervalType

• You can drop the parentheses surrounding scheduledTasks[intCount] but that's as far as you can go without changing to as casting or using local variables... – BoltClock Jun 25 '11 at 3:53

Somewhat better:

(scheduledTasks[intCount] as ScheduledTask).TaskIntervalType


Note that the behavior would be somewhat different: The as cast will not throw an exception when not successful, but return null - so you would get a NullReferenceException (when trying to access the property on a null reference) instead of a cast exception.

• Not equivalent statement. – Alex Aza Jun 25 '11 at 3:55
• If you are sure that that the value is ScheduledTask and that it is not null then using ((ScheduledTask)(scheduledTasks[intCount])) is better form performance than using as keyword – Jalal Said Jun 25 '11 at 3:57
• Indeed, not equivalent. Not only does it throw a NullReferenceException instead of an InvalidCastException (thus making it harder to debug what went wrong), the as operator also doesn't use custom conversions defined by classes which the original does. – Sven Jun 25 '11 at 3:59
• @Sven It does not throw NullReferenceException. It simply returns null. – Adam Lear Jun 25 '11 at 4:03
• The as operator itself doesn't throw a NullReferenceException, but his code does because it tries to use the result without checking for null. – Sven Jun 25 '11 at 4:25
var task = (ScheduledTask)scheduledTasks[intCount];


You could use the as keyword instead:

var task = scheduledTasks[intCount] as ScheduledTask;


but it would change the behaviour of the cast. For one, as noted, it will return null instead of throwing an exception for a failed conversion. For another, it will not perform any custom conversions between types that you might have.

Although with that said, using as is probably better than casting because it behaves in a more consistent and reliable way than a cast.

And with all that said, perhaps the right approach would be to change your array to be strongly typed or expose the TaskIntervalType as a property on an interface or base class? That way casting would not be needed at all.

For example,

public interface ITask
{
}

{}

public MyStuff()
{
// populate the list, etc...

/// ... and back to your example:
}

• If I was a var advocate this would rock. Unfortunately my preference is that I don't like the var keyword. I don't want to get into that debate either but thanks for your post...this is a useful reply to people who are var advocates or willing to embrace var :). – CoffeeAddict Jul 10 '11 at 4:20
• @CoffeeAddict Nothing I wrote requires you to use var. Feel free to replace it with explicit types. :) – Adam Lear Jul 10 '11 at 4:35

It could be safer (not sure about the variable names and types):

    ScheduledTask Task =  scheduledTasks[intCount] as ScheduledTask;