Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use (ObjectType) or 'as ObjectType' when casting in c#? [duplicate]

Tags:

c#

casting

Possible Duplicate:
Casting: (NewType) vs. Object as NewType

Say for example I have a class called MyObjectType and I want to convert the sender parameter of an event to this type. I would usually go about it by simply doing this:

MyObjectType senderAsMyType = (MyObjectType) sender;

I've recently realised that it can also be done like this:

MyObjectType senderAsMyType = sender as MyObjectType;

Which way is most efficient? So that I can make my code consistent and use one of the ways throughout. Or do they both have pro's and cons? If so please could someone inform me of them.

Thanks again,

like image 736
Lloyd Powell Avatar asked Mar 01 '23 12:03

Lloyd Powell


1 Answers

If you wish to avoid any InvalidCastExceptions use

MyObjectType senderAsMyType = sender as MyObjectType;

otherwise use

MyObjectType senderAsMyType = (MyObjectType)sender;

if an InvalidCastException represents a true exceptional situation in your application.

As for performance, I would contend that you would find no discernible difference between the two different kinds of casting. I was interested though so I used Jon Skeet's BenchmarkHelper and achieved results that confirmed my suspicions:

Test:

using System;
using BenchmarkHelper;

class Program
{
    static void Main()
    {
        Object input = "test";
        String output = "test";

        var results = TestSuite.Create("Casting", input, output)
            .Add(cast)
            .Add(asCast)
            .RunTests()
            .ScaleByBest(ScalingMode.VaryDuration);
        results.Display(ResultColumns.NameAndDuration | ResultColumns.Score,
                results.FindBest());
    }

    static String cast(Object o)
    {
        return (String)o;
    }

    static String asCast(Object o)
    {
        return o as String;
    }

}

Output:

============ Casting ============
cast   30.021 1.00
asCast 30.153 1.00
like image 141
Andrew Hare Avatar answered Apr 26 '23 16:04

Andrew Hare