Search code examples
c#initializationas-keyword

Why initialize an object using as keyword


I've just run across some code I don't understand. It is effectively

Class c = new BaseClass() as Class;

I don't understand the advantage of doing this, so I created my own console application to see what it does.

namespace Initialize
{
    class Program
    {
        static void Main(string[] args)
        {
            Demo demo = new Demo();
            demo.BaseProp = "";
            demo.DemoProp = "";

            BaseDemo baseDemo = new BaseDemo();
            baseDemo.BaseProp = "";

            BaseDemo baseDemo2 = new Demo();
            baseDemo2.BaseProp = "";

            BaseDemo baseDemo3 = new Demo() as BaseDemo;
            baseDemo3.BaseProp = "";

            //fails runtime
            //Demo demo2 = (Demo)baseDemo;

            Demo demo3 = (Demo)baseDemo2;
            demo3.BaseProp = "";
            demo3.DemoProp = "";

            Demo demo4 = (Demo)baseDemo3;
            demo4.BaseProp = "";
            demo4.DemoProp = "";
        }
    }

    class BaseDemo
    {
        public string BaseProp { get; set; }
    }

    class Demo : BaseDemo
    {
        public string DemoProp { get; set; }
    }
}

I can only assume this offers some additional help in relation to polymorphous but I can't work out how or see any difference between:

BaseDemo baseDemo2 = new Demo();  

and

BaseDemo baseDemo3 = new Demo() as BaseDemo;

Solution

  • This

    Class c = new BaseClass() as Class;
    

    is totally useless. If Class is a base class of BaseClass then the cast was automatic, otherwise the cast will always return null.

    Class c = new BaseClass()
    

    was enough... Single exception:

    var c = new BaseClass() as Class;
    

    now c is a reference of type Class (but referencing a BaseClass). You are forcing the type of an implicit typed variable (quite useless... you could have written directly Class c = new BaseClass();)

    Note that the as keyword, contrary to the cast operator () doesn't "activate" the implicit/explicit cast operator that one of the two classes could have implemented.

    This won't compile:

    class BaseClass
    {
        public static implicit operator Class(BaseClass b)
        {
            return new Class();
        }
    }
    
    class Class
    {            
    }
    
    Class c = new BaseClass() as Class;
    

    As written in the msdn:

    The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.

    and

    Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.