Using implicit And explicit Keywords

By Michael Detras

Here is an example on how to use implicit and explicit keywords. These are used for user-defined conversions.

The following example shows a class called DataType and we can convert an object to a Type class and vice-versa. When converting from Type to DataType, we don't need to specify a cast operator since this is done implicitly. When converting from DataType to Type, we have to specify a cast operator because of the explicit keyword.

public
class DataType
{
    private DataType(Type type)
    {
       AssemblyQualifiedName = type.AssemblyQualifiedName;
    }

    public Type GetTypeFromAssemblyQualifiedName()
    {
         return Type.GetType(AssemblyQualifiedName);
    }

    public static implicit operator DataType(Type type)
    {
         return new DataType(type);
    }

    public static explicit operator Type(DataType dataType)
    {
         return dataType.GetTypeFromAssemblyQualifiedName();
    }

    public string AssemblyQualifiedName { get; set; }
}

Using implicit And explicit Keywords  (497 Views)