Click to See Complete Forum and Search --> : How to restrict data passed


Marraco
April 10th, 2008, 10:02 AM
I are coding a generic class that works as red black balanced binary tree. I wanna post it here when finished.

(Is a shame that .NET does not have it predefined, like the array class.)

That data structure will store objects types, to be sure that the user can store his own objects.

My class declare the user object this way:
Public Module Red_Black_Tree
Private Class Node
Public Data As Object 'Each Data to store in this tree
...But I need to force the user to use only Object witch implements the Icomparable interface.

I have two questions:

1-żIs there a way to declare this line Public Data As Object to restrict it only to objects with Icomparable interface (or another workaround).?

2-When the new() subroutine is called, to create a new data, I can Try utilize the Icomparable interface, and if it does not have it, then trow an error (surely the same exception on the Try...End Try block of code), but I would like to have a specific way to check that it implements the Icomparable interface.

dglienna
April 10th, 2008, 10:58 AM
How about a ListOf() with type-safety?

Havok
April 10th, 2008, 10:59 AM
Im not pretty sure what are you exactly doing, but I think you are not taking the right direction in this one.

However, here are my responses to your questions.

1) You can declare the object to be a IComparable

Dim obj_Data As IComparable

This obj_Data will only accept instances of objects that have IComparable

2) When you want to check if an object has the IComparable interface you do this boolean expression:

If TypeOf obj_Data Is IComparable Then

Of course you can erase the IF-THEN.

Marraco
April 10th, 2008, 11:50 AM
Im not pretty sure what are you exactly doing, but I think you are not taking the right direction in this one.I want to store generic Object variables on a specific data structure. "Physically" I plan to store an array of those objects, but that must be transparent to the programmer, who just need to know that (since I are doing a balanced binary tree) each new data is inserted automatically sorted.

That structure of data is fast to insert new data, and to search data.

The user gonna add new data with a line like:
MyTree.Add(MyObject) Thus the class gonna have a Sub like: Public Sub Add(NewItem as Object)
'Code to add the NewItem to efficient data structure.

'NewItem needs to implements an Icomparable interface,
'Since I need to access his .CompareTo function
end sub 'Add
However, here are my responses to your questions.

1) You can declare the object to be a IComparable

Dim obj_Data As IComparable It looks like the answer: "Public Sub Add(NewItem as IComparable)" I gonna try that :)

...
2) When you want to check if an object has the IComparable interface you do this boolean expression:

If TypeOf obj_Data Is IComparable Then
....It also looks like the answer.