dotNET
dotNET

Reputation: 35450

Is there a built-in generic class for this in .NET?

Is there a class that is precisely equal to this class?

Class X(Of T)
    Public value As T
End Class

Note that neither Nullable(Of T) nor Tuple(Of T) are equal to this class because they do not allow you to set the member value. The class should have the following properties:

  1. When passed as parameter, any changes made by the called method should affect the sent object, i.e. it should not create a copy of object as it does for intrinsic types.
  2. Should allow setting the member value to a value using syntax x.value = <some value> where x is an object of X.

Upvotes: 0

Views: 207

Answers (2)

supercat
supercat

Reputation: 81307

I've sometimes created such a class, almost verbatim, although I called the class Holder<T> and the field Value; there are two nice usage cases for such a class:

  • Given a collection of Holder<someValueType>, it's possible to perform convenient in-place modifications of the contents of the collection. For example, given a List<Holder<Point>>, one can say MyList[3].Value.X += 5;.

  • If T is of a type that permits atomic operations, one may perform thread-safe atomic operations on the contents of a collection of Holder<T> even if the collection is not threadsafe. For example, in one scenario where I knew in advance all of the keys I'd need for a dictionary, I created a Dictionary<String, Holder<Integer>> and then could have multiple threads use Interlocked.Increment to count how many times each of those strings appeared. Even though Dictionary was not thread-safe, the program was thread-safe without locking because the set of Holder<Integer> items stored in the dictionary never had to change.

If you want to use a built-in type, there is one that would work: a T[] with size one. The main disadvantage of that type is that there's nothing inherent in the type which guarantees that element zero will actually exist (i.e. that it won't be an empty array).

Upvotes: 1

Ric
Ric

Reputation: 13248

Not a conclusive answer, but i'll give it a go.

I personally have not seen this type of class before. Even the documentation on generics shows an example class similar to yours being created and used in the examples:

msdn generics in the .net framework.

Here's the example:

Public Class Generic(Of T)
    Public Field As T

End Class

....

Public Shared Sub Main()
    Dim g As New Generic(Of String)
    g.Field = "A string" 
    '...
    Console.WriteLine("Generic.Field           = ""{0}""", g.Field)
    Console.WriteLine("Generic.Field.GetType() = {0}", g.Field.GetType().FullName)
End Sub

Upvotes: 1

Related Questions