tags:

views:

165

answers:

3

primitive types (integer, string, etc) are now classes. However to access the value of the class you just use the object name (ex, x=y). It isn't necessary to refer to a property of the class (x.value = y.value).

To implement an abstract data class (say inches), we need a value property so if we have dim x as inches (our class) we have to use: x.value = 3

is that fair?

+5  A: 

You have the option of overloading the assignment operator to suite your needs.

For example:

public static implicit operator Inches(int value)
{
   return new Inches(value);
}

At which point you would then be able to do something like so:

Inches something = 4;
Joseph
Just so you know, the question is tagged as "vb.net".
Andrew Hare
@Andrew: Is this not doable in VB.NET? Or are you just pointing that out because the answer was given in C#?
BFree
@Andrew Hare - also tagged as C#
heavyd
@Andrew It's not tagged in both VB.NET and C#?
Joseph
sorry, Joseph - I thought c# had the same problem as vb.net since I was really interested in the vb.net solution. vb.net doesn't allow you to override the assign as far as I know.
A: 

Another example:


class Program
{
    class A
    {
        private int _x;
        public A(int x)
        {
            _x = x;
        }

        public static implicit operator int(A a)
        {
            return a._x;
        }
    }
    static void Main(string[] args)
    {
        A a = new A(3);
        Console.WriteLine(a);
    }
}

Hans Malherbe
+5  A: 

I think what you are looking for is an implicit conversion to and from a primitive type. Joseph gave part of the C# code, here is the VB.Net version (with both operator types)

Class Inches
    Private _value As Integer
    Public ReadOnly Property Value() As Integer
        Get
            Return _value
        End Get
    End Property
    Public Sub New(ByVal x As Integer)
        _value = x
    End Sub

    Public Shared Widening Operator CType(ByVal x As Integer) As Inches
        Return New Inches(x)
    End Operator

    Public Shared Widening Operator CType(ByVal x As Inches) As Integer
        Return x.Value
    End Operator
End Class

This allows you to write the following code

    Dim x As Inches = 42
    Dim y As Integer = x
JaredPar
Thanks Jared, I couldn't find anything on how to do this in VB.NET
Joseph
very slick. Thank you