1
votes

Is is possible to define (perhaps) an operator for a class which could enable using 'as' conversion?

The point is:

class C
{
   string a;
   string b;

   public C what_here(string s)
   {
      a = s.Substring(0, 2);
      b = s.Substring(3);
   }
}

The class' use:

("something" as C).a;

This gives:

Error CS0039: Cannot convert type 'string' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

P.S. the true class C is much bigger, the point is just how to enable the as operator, which I just got used to...

1
Possible duplicate of What is a wrapping conversion? - Jamie Rees
look up operator overloading such as implicit or explicit casts - Daniel A. White
Cant you use a constructor and pass the string as an argument rather than cast it? new C("Something").a. I Suppose my question to you is, why do you need to cast the object? - Kieran Devlin
FYI: With regard to reference types/classes, boxing/unboxing cannot be "enabled" as boxing/unboxing simply doesn't make sense with reference types. (Boxing/unboxing is what happens to values of value types if they need to be passed as reference, like int a = 5; object o = a; int b = (int) o;) - user2819245

1 Answers

0
votes

As per the docs for as:

Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

So you won't be able to use as to invoke an implicit operator.

However, if you're prepared to use implicit or explicit casting:

class C
{
   // Obviously you want to encapsulate these as properties, not fields
   public string a;
   public string b;

   public static implicit operator C(string s)
   {
      var localA = s.Substring(0, 2);
      var localB = s.Substring(3);
      return new C
      {
         a = localA,
         b = localB
      };
   }
}

void Main()
{
    C myC = "AA BBBBBBBB"; // Or explicitly, var myC = (C)"AA BBBBBBBB"
    Console.WriteLine(myC.a);
    Console.WriteLine(myC.b);
}

Output:

AA
BBBBBBBB

But! Don't abuse the conversion operators

As per @Kieran's comment, conversion operators, when used in arbitrary ways, can be really difficult for others to read. It's not particularly intuitive that a string should automagically be converted into your own custom class. IMO the following alternatives are easier to read.

A constructor overload:

var myC = new C("string to parse here");

or an extension method:

var myC = "string to parse here".ToC();  

where ToC will be the same code as the conversion operator, but with the signature public static C ToC(this string s).