class Person
{
string Name;
int Age;
}
I want to be able to cast a string to Person implicitly like following
var mrFoo = "Foo" as Person;
I know I can do the following by defining implicit casting
Person mrFoo = "Foo";
But I'm specific to use "as" operator
No, you can't do that. The "as" operator never uses user-defined conversions - only reference conversions and unboxing conversions. Basically, the reference in question already has to be the right type.
Personally I would strongly advise you to stay away from conversion operators (especially implicit ones) for the vast majority of cases. Usually having a conversion method is clearer, e.g. Person.FromString(...)
.
Have you considered using a parameterized constructor?
var mrFoo = new Person("Foo");
No need to use the as
operator, since you can do this with the implicit
operator: http://msdn.microsoft.com/en-us/library/z5z9kes2(v=vs.71).aspx
Something along these lines should work:
public static implicit operator Person(string s)
{
Person p = new Person() {Name = s};
return p;
}
Now you can simply do:
Person p = "John Doe";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With