Search code examples
c#.netcastingtype-systemsas-operator

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, I assign it to the Tag property of another object:

line.Tag = new Call(sf1, sf2);

But when I try to retrieve the Tag property like so,

Call call = line.Tag as Call;

Visual Studio gives the following compile-time error:

The operator as must be used within a reference type or nullable type

What is the meaning of that? And how can I solve it?


Solution

  • A struct is a value type, so it cannot be used with the as operator. The as operator must be able to assign a value of null if the cast fails. This is only possible with a reference type or a nullable value type.

    There are a couple ways to solve this, but your best bet is to change your Call type from a struct to a class. This will essentially change your type from a value type to a reference type, which allows the as operator to assign a value of null if the cast fails.

    For more information on value types vs. reference types, this is a decent article. Also, have a look on MSDN: