Class Extension for type Conversion

JaedenRuiner

Well-known member
Joined
Aug 13, 2007
Messages
340
Programming Experience
10+
Is there a way to write an extension that handle Implicit type conversions of objects, but the same as Structures/Classes can be written with Operators that handle the multi-various operations that could be applied to an object.

See, I know people will disagree, but three classes should never be so painstaking to deal with:
Char, Byte, String.

A char and string are interchangeable, save for the length, even Java knows that. You can't set a Char to String, because a Char is a Simple type, unsigned 8 bit value, where a string is technically a reference type pointing to multiple bytes of chars (whether they be multi-byte chars or single byte doesn't matter). It is a Byte that happens be referenced via the ascii chart as opposed to straight up numerics. Strings are multiple chars.
Array of Char() = A STRING, and the conversion should be automatic. I can't even do a CType(Char, Byte) to get the value.

C, C++, Delphi, Java, all can do these simple things, but VB can't...so naturally I want to hack it. *chuckle*

I'm already writing Char() array extensions that will handle some of it, but I was wondering if I could some how, "hard code" certain operations like how I can write a Narrowing/Widening conversion operator CType() for a Structure or Class.

Thanks
 
First up, Char are 16 bits, not 8 bits, so there is no direct correspondence between a Char and a Byte. ASCII characters can be represented with a single byte but the .NET Char type was created to inherently support Unicode.

.NET Chars can already be assigned directly to String variables because the conversion is widening and therefore allowed by Option Strict On. If you want to create a Char from a Byte you just use:
VB.NET:
Dim myChar As Char = Convert.ToChar(myByte)
or you can use Chr or ChrW if you prefer. There's also Convert.ToByte for the reverse. To get a Char from a String you just index it with zero:
VB.NET:
Dim myChar As Char = myString(0)
As for Char arrays to Strings and back, the String class has a ToCharArray method and a constructor that takes a Char array.

You really are trying to solve a problem that doesn't exist. All those types have simple methods for converting between them. As for creating extensions, extension methods are exactly that: methods. They exist to support LINQ and LINQ doesn't need to extend types with operators.
 
They exist to support LINQ and LINQ doesn't need to extend types with operators.
Ahh. Figured. Oh well. Thanks for the info though. Especially the Unicode bit. I didn't know .Net automatically supported MultiByte Chars. i'm so used to that being the other way around. Like Pascal Char and WChar, and PChar and PWideChar. It makes sense though, now that you mention it.
 
Back
Top