I try to describe my problem step by step because I do not know how to say it in correct programming terms.
When I use a System.String type, I do the following:
Dim Str1 as String
Str1 = "This is a string"
I want to create a new type that just like the System.String type but in different name. For example, I want to create a UrlString type for string like this:
Dim Str2 as UrlString
Str2 = "http://www.example.com"
My question is: How do I create the UrlString type?
The reason: I want to create the UrlString type to help me to identify the value of the content. For example, UrlString type means the string is in url format, PhoneString means the string is in phone format, CreditCardString type means the string is in credit card format and so on.
UPDATE:
Thanks Marc Gravell and GSerg. Here is the solution:
Class UrlString
Private ReadOnly value As String
Public Sub New(ByVal value As String)
Me.value = value
End Sub
Public Shared Widening Operator CType(ByVal value As String) As UrlString
Return New UrlString(value)
End Operator
Public Shared Widening Operator CType(ByVal u As UrlString) As String
Return u.value
End Operator
Public Overrides Function GetHashCode() As Integer
Return If(value Is Nothing, 0, value.GetHashCode())
End Function
Public Overrides Function Equals(ByVal obj As Object) As Boolean
Return String.Equals(value, DirectCast(obj, String))
End Function
Public Overrides Function ToString() As String
Return value
End Function
End Class
Use the Substring method to create a new string from a part of the original string. You can search for one or more occurrences of a substring by using the IndexOf method. Use the Replace method to replace all occurrences of a specified substring with a new string.
"string" is just an alias of System. String and both are compiled in the same manner. String stands for System.
" System. String " a.k.a "String" (capital "S") is a . NET framework data type while "string" is a C# data type. In short "String" is an alias (the same thing called with different names) of "string".
You need to add an implicit conversion operator from string
to UrlString
for that to work. In C#:
class UrlString
{
private readonly string value;
public UrlString(string value) { this.value = value; }
public static implicit operator UrlString(string value)
{
return new UrlString(value);
}
public override int GetHashCode()
{
return value == null ? 0 : value.GetHashCode();
}
public override bool Equals(object obj)
{
return string.Equals(value, (string)obj);
}
public override string ToString()
{
return value;
}
}
Then:
UrlString foo = "abc";
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