Questions tagged [as-operator]

The c# as operator is used to convert between compatible reference or nullable types. It is similar to a cast operation, except that it will set the result of the conversion to null for a failed conversion, rather than throwing an exception.

The following is an excerpt from the official C# 4.0 specification:

7.10.11 The as operator The as operator is used to explicitly convert a value to a given reference type or nullable type. Unlike a cast expression (§7.7.6), the as operator never throws an exception. Instead, if the indicated conversion is not possible, the resulting value is null.

In an operation of the form E as T, E must be an expression and T must be a reference type, a type parameter known to be a reference type, or a nullable type. Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs:

  • An identity (§6.1.1), implicit nullable (§6.1.4), implicit reference (§6.1.6), boxing (§6.1.7), explicit nullable (§6.2.3), explicit reference (§6.2.4), or unboxing (§6.2.5) conversion exists from E to T.

  • The type of E or T is an open type.

  • E is the null literal.

If the compile-time type of E is not dynamic, the operation E as T produces the same result as

E is T ? (T)(E) : (T)null

except that E is only evaluated once. The compiler can be expected to optimize E as T to perform at most one dynamic type check as opposed to the two dynamic type checks implied by the expansion above.

If the compile-time type of E is dynamic, unlike the cast operator the as operator is not dynamically bound (§7.2.2). Therefore the expansion in this case is:

E is T ? (T)(object)(E) : (T)null

Note that some conversions, such as user defined conversions, are not possible with the as operator and should instead be performed using cast expressions.

In the example

class X
{

    public string F(object o) {
        return o as string;     // OK, string is a reference type
    }

    public T G<T>(object o) where T: Attribute {
        return o as T;          // Ok, T has a class constraint
    }

    public U H<U>(object o) {
        return o as U;          // Error, U is unconstrained 
    }
}

the type parameter T of G is known to be a reference type, because it has the class constraint. The type parameter U of H is not however; hence the use of the as operator in H is disallowed.

17 questions
30
votes
7 answers

When should you use the as keyword in C#

When you want to change types most of the time you just want to use the traditional cast. var value = (string)dictionary[key]; It's good because: It’s fast It’ll complain if something is wrong (instead of giving object is null exceptions) So…
Daniel Little
  • 16,975
  • 12
  • 69
  • 93
27
votes
6 answers

Why can't I use the as keyword for a struct?

I defined the following struct: public struct Call { public SourceFile caller; public SourceFile callee; public Call(SourceFile caller, SourceFile callee) { this.caller = caller; this.callee = callee; } } Later,…
anon
24
votes
3 answers

The as operator on structures?

I don't get it. The As operator: Then why does the following work? struct Baby : ILive { public int Foo { get; set; } public int Ggg() { return Foo; } } interface ILive { int Ggg(); } void Main() { ILive i = new…
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
17
votes
1 answer

How is "as" operator translated when the right-side operand is generic?

I have just posted an answer to this question but I'm not entirely convinced of my answer.There are two things I'm wondering, consider this code: class Foo { void SomeMethod() { string str = "foo"; Foo f = str as…
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
8
votes
3 answers

Is the as operator with a nullable value type unnecessarily slow?

Consider this code: static void FillUsingAsNullable() { int?[] arr = new int?[1 << 24]; var sw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < arr.Length; ++i) arr[i] = GetObject() as int?; Console.WriteLine("{0:N0}",…
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
7
votes
2 answers

IConfiguration.GetSection() as Properties returns null

I'm trying to retrieve configuration inside my application. I have passed the IConfiguration into the service class which needs to pull some settings. The class looks a bit like this: private IConfiguration _configuration; public…
PeaceDealer
  • 977
  • 2
  • 9
  • 20
6
votes
7 answers

How to use "Sender" parameter with "As" operator for more then one class at a time?

In Delphi, sometimes we need to do this... function TForm1.EDIT_Click(Sender: TObject); begin (Sender As TEdit).Text := ''; end; ...but sometimes we need to repeat the function with other object class like... function…
NaN
  • 8,596
  • 20
  • 79
  • 153
5
votes
6 answers

Casting one object to another type

I have one class named A and one class B public class A : UserControl { } public class B : UserControl { } Now i have one assembly whose class's function accepts objects of class A. This assembly is not created by me so i don't have any control.…
TCM
  • 16,780
  • 43
  • 156
  • 254
3
votes
2 answers

How to use variable type in as operator

For example:I have 2 variable (value ) & (property) i want to check is cast possible for value? We do not know the type of variables, How to check if cast is possible? var value = Reader[item]; PropertyInfo property = properties.Where(x =>…
masoud
  • 53
  • 9
3
votes
1 answer

ActionResult as ViewResult returns null.. but I can explicitly cast?

I'm writing some unit tests and I have a scenario where, if a condition is true, a controller action should return a HttpNotFoundResult, otherwise it should return a ViewResult and have a specific Model inside of it. As one of the tests (testing the…
Dan
  • 10,282
  • 2
  • 37
  • 64
1
vote
4 answers

would `as` enable polymorphism? would pass a inherited class to a method which takes a base class enable polymorphism?

Fist of all, I will use virtual and override for example, base class A has method A.do(), inherited class B has B.do() which overrides A's. if I call (B as A).do(), which do() would it execute? or, if there is a method void mymethod(A a) {a.do()},…
colinfang
  • 20,909
  • 19
  • 90
  • 173
1
vote
3 answers

C# / .NET - operator AS performance/approach

Im working on a e-commerce sort of application. Entities are: Product with List Expenses Expense with Description props which is referring to packaging, transport, administrative costs etc. I need to have at least 2 types of…
Context
  • 53
  • 5
1
vote
1 answer

how to cast Action to Action

public class SettingsBase { } public class SettingsDerived : SettingsBase { } public class yyy { public void StartUpMethod(Action settings) { //something goes here.. SettingsDerived ds = new…
techBeginner
  • 3,792
  • 11
  • 43
  • 59
0
votes
2 answers

Type casting vs as operator in C#

What is the difference between Type casting and as operator in C#. For example in this code: class LivingThing { public int NumberOfLegs { get; set; } } class Parrot : LivingThing { } interface IMover { void Move(T…
ali kh
  • 9
  • 1
-1
votes
1 answer

Cast to one of two types in C#

How can I cast to one of two types in C#? Here is what I am trying to do: public class BaseCl {} public class Foo : BaseCl {} public class Bar : BaseCl {} BaseCl instance; ... some code which puts a value in the `instance` var specificInstance =…
qqqqqqq
  • 1,831
  • 1
  • 18
  • 48
1
2