7.3. Boxing and Constraints
In some cases, the application of type constraints will actually prevent your value type parameters from being boxed. Suppose, for example, you had the following interface and structure that you wanted to use to manage stock prices:
[VB code] Public Interface IPriceTicker Sub UpdatePrice(ByVal newPrice As Double) Function ToString() As String End Interface Public Structure Stock Implements IPriceTicker Private currentPrice As Double Public Sub UpdatePrice(ByVal newPrice As Double) _ Implements IPriceTicker.UpdatePrice Console.Out.WriteLine("Updating With Price: {0}", newPrice) currentPrice = newPrice End Sub Public Overrides Function ToString() As String Implements IPriceTicker.ToString Return currentPrice.ToString() End Function End Structure
[C# code] public interface IPriceTicker { void UpdatePrice(double newPrice); } public struct Stock : IPriceTicker { Private double currentPrice; public void UpdatePrice(double newPrice) { Console.Out.WriteLine("Updating With Price: {0}", newPrice); currentPrice = newPrice; } public override string ToString() { return currentPrice.ToString(); } }
The Stock structure introduced here is meant to represent a simple value type that, through its implementation of the IPriceTicker interface, allows clients to change the value of a stock. Now, put together a couple of clients that will create a Stock and feed it some new prices:
[VB code] Public Class PriceTest Public Sub ProcessPrices1(Of T As New)(ByVal prices As Double()) ...
Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.