Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading/implicit operator for 'as'

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

like image 504
Nasmi Sabeer Avatar asked Jun 01 '11 15:06

Nasmi Sabeer


3 Answers

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(...).

like image 91
Jon Skeet Avatar answered Nov 10 '22 14:11

Jon Skeet


Have you considered using a parameterized constructor?

var mrFoo = new Person("Foo");

like image 37
Brian Avatar answered Nov 10 '22 14:11

Brian


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";
like image 26
matt Avatar answered Nov 10 '22 16:11

matt