Search code examples
c#as-keyword

Object initializations are lost through use of "as" keyword


I am using a derived class and casting the base class to it using the as keyword. When I do this, the derived class constructor is being called, and it's objects initialized, but the derived instance does not end up with the initialized objects (has nulls). Here's a code sample.

// classes
public class Request
{
  public Request();
  public Header Header{get;set;}
}

public class CreateRequest : Request
{
  public Foo Foo{get;set;}
  public Bar Bar{get;set;}

  public CreateRequest():base()
  {
    this.Foo = new Foo();
    this.Bar = new Bar();
  }
}

public class SomeClass
{
  private Response ProcessCreateRequest(Request request)
  {
    // request comes from a json request
    CreateRequest createRequest = request as CreateRequest;
    // values of Foo and Bar are null
    [...]
  }
}

Is the problem that "as" is normally used for derived->base and not base->derived or is there something else at work here?


Solution

  • until jon skeet shows up to correctly answer this question, as far as i know the 'as' keyword is just a way of doing a cast that suppresses exceptions if the cast is invalid; it should not call any constructors on its own

    so have you verified (e.g. in the debugger) that the passed-in object is properly initialized before the cast?