Click or drag to resize

ExtensionsConvertionsAsT Method (Object)

Performs a cast between compatible reference types. If a convertion is not possible then null is returned. As a last resort it will use ChangeType(Object, Type).

Tries to use the implicit and explicit operators if exists when convertion with 'as' returns null.

Namespace:  Cauldron
Assembly:  Cauldron (in Cauldron.dll) Version: 3.2.0.2
Syntax
public static T As<T>(
	this Object source
)
where T : class

Parameters

source
Type: SystemObject
The object to convert

Type Parameters

T
The Type to convert to

Return Value

Type: T
The object casted to T

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type Object. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).
Examples
In the following code example, the 'As' extension is used to convert a returned object via the implicit operator.
public interface IFoo
{
    string Name {get;}
    string Description {get;}
}

public class Foo : IFoo
{
    public string Name {get; set;}
    public string Description {get; set;}
}

public class Bar : BarBase
{
    private IFoo internalFoo;

    private Bar(IFoo foo)
    {
        this.internalFoo = foo;
    }

    public void DoSomeStuff()
    {
    }

    public void DoSomeOtherStuff()
    {
    }

    public static implicit operator Bar(Foo value) => new Boo(value);
    public static implicit operator Foo(Bar value) => value.internalFoo;
}

public class SomeOtherClass
{
    public IFoo GetFooFromSomewhere(string fooId) => new Foo { Name = "A Foo", Description = "This is the foo you are looking for." };
}
The code can be called like following:
var bar = someOtherClassInstance.GetFooFromSomewhere("fooThatINeed").As<Bar>();
See Also