You can use the [static] implicit operator feature of C# ([Shared] Widening Operator in VB) to implicitly convert types. For example, suppose you have this class:
class Foo
{
public Foo(int age)
{
this.Age = age;
}
}
With the correct implicit operator, you could instantiate the object as so:
Foo foo1 = 35;
So, why would you want to do this? Well, probably in general, you might be leery (for good reason) of adding “implicitness” to your code, so approach doing so with caution. It can be confusing to throw something atypical like this in code. However, a fellow colleague of mine used this feature to effectively mimic subclassing the stringclass in a useful way. He did this by declaring a simple type containing an implicit operator (taking in the custom type, and returning a string). That custom type was used as the type for parameters instead of string, and hence the “enforcement” of the “custom string”. At the point the type needed to be a string, the implicit operator was used, so that an instance could be passed wherever a string was needed as well. In this case, it was like using a c# const, but the available strings were typed analogous to using an enum for integers. This example could be taken further by inheriting interfaces and/or additional base classes to have different classes of “typed strings”.
Here’s the compete Foo example followed by the view from Reflector:
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Foo foo1 = 35;
PrintFoo(foo1);
}
private static void PrintFoo(int age)
{
Console.WriteLine("Foo's age: {0}", age);
}
}
class Foo
{
public Foo(int age)
{
this.Age = age;
}
public int Age { get; set; }
public static implicit operator Foo(int age)
{
return new Foo(age);
}
public static implicit operator int(Foo foo)
{
return foo.Age;
}
}
}
Here’s what it looks like in reflector. You’ll note the compiler changes to an explicit conversion when calling PrintFoo)