Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5963535
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T19:16:13+00:00 2026-05-22T19:16:13+00:00

I know there are several posts already concerning the difference between casts and the

  • 0

I know there are several posts already concerning the difference between casts and the as operator. They all mostly restate the same facts:

  • The as operator will not throw, but return null if the cast fails
  • Consequently, the as operator only works with reference types
  • The as operator will not use user-defined conversion operators

Answers then tend to debate endlessly the how to use or not use the one or the other and the pros and cons of each, even their performance (which interests me not at all).

But there is something more at work here. Consider:

static void MyGenericMethod<T>(T foo)
{
    var myBar1 = foo as Bar;  // compiles
    var myBar2 = (Bar)foo;    // does not compile ('Cannot cast expression of
                              // type 'T' to type 'Bar')
}

Please never mind whether this obviously contrite example is good practice or not. My concern here is the very interesting disparity between the two in that the cast will not compile whereas the as does. I really would like to know if anyone could shed some light on this.

As is often noted, the as operator disregards user-defined conversions, but in the above example, it is clearly the more capable of the two. Note that as far as the compiler is concerned, there is no known connection between the (unknown at compile-time) type T and Bar. The cast is entirely ‘run-time’. Should we suspect that the cast is resolved, wholly or partly, at compile time and the as operator not?

By the way, adding a type constraint unsurprisingly fixes the cast, thus:

static void MyGenericMethod<T>(T foo) where T : Bar
{
    var myBar1 = foo as Bar;  // compiles
    var myBar2 = (Bar)foo;    // now also compiles
}

Why does the as operator compile and the cast not?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T19:16:14+00:00Added an answer on May 22, 2026 at 7:16 pm

    To address your first question: it is not just that the as operator disregards user-defined conversions, though that is relevant. What is more relevant is that the cast operator does two contradictory things. The cast operator means either:

    1. I know that this expression of compile-time type Foo will actually be an object of runtime-type Bar. Compiler, I am telling you this fact now so that you can make use of it. Please generate code assuming that I am correct; if I am incorrect, then you may throw an exception at runtime.

    2. I know that this expression of compile-time type Foo will actually be of runtime type Foo. There is a standard way of converting some or all instances of Foo to an instance of Bar. Compiler, please generate such a conversion, and if it turns out at runtime that the value being converted is not convertible, then throw an exception at runtime.

    Those are opposites. Neat trick, to have an operator that does opposite things.

    The as operator by contrast only has the first sense. An as only does boxing, unboxing and representation-preserving conversions. A cast can do all of those plus additional representation-changing conversions. For example, casting int to short changes the representation from a four-byte integer to a two-byte integer.

    That’s why “raw” casts are not legal on unconstrained generics; because the compiler does not have enough information to figure out what kind of cast it is: boxing, unboxing, representation-preserving or representation-changing. The expectation of users is that a cast in generic code has all the semantics of a cast in more strongly typed code, and we have no way to generate that code efficiently.

    Consider:

    void M<T, U>(T t, out U u)
    {
        u = (U)t;
    }
    

    Do you expect that to work? What code do we generate that can handle:

    M<object, string>(...); // explicit reference conversion
    M<string, object>(...); // implicit reference conversion
    M<int, short>(...); // explicit numeric conversion
    M<short, int>(...); // implicit numeric conversion
    M<int, object>(...); // boxing conversion
    M<object, int>(...); // unboxing conversion
    M<decimal?, int?>(...); // lifted conversion calling runtime helper method
    // and so on; I could give you literally hundreds of different cases.
    

    Basically we would have to emit code for the test that started the compiler again, did a full analysis of the expressions, and then emitted new code. We implemented that feature in C# 4; it’s called “dynamic” and if that’s the behaviour you want, you can feel free to use it.

    We have none of these problems with as, because as only does three things. It does boxing conversions, unboxing conversions, and type tests, and we can easily generate code that does those three things.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know there are several plugins that do asynchronous processing. Which one is the
I know there are several ways to deploy a .net windows client application: There's
I know it is easy to recommend several cross platform libraries. However, are there
From several posts inside stackoverflow and outside, I have come to know how to
As we know there are several methodology for http connection. My social network application
I've read several of the posts on stack overflow already about this topic, but
I know that it seems a duplicate entry, but I red all the posts
I know there is a registry key indicating the install directory, but I don't
I know there are a lot of positive things mod-rewrite accomplishes. But are there
I know there are quite a few line count tools around. Is there something

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.