Kurt Posted January 21, 2004 Posted January 21, 2004 A user of my class needs to supply some information to the constructor of the class. Then the constructor checks if the parameters that where passed can describe a valid instance or not. If not I give the user a warning, but I would also like to drop the creation of the object itself - as if the constructor was never called! Is this possible? Quote qrt
Administrators PlausiblyDamp Posted January 21, 2004 Administrators Posted January 21, 2004 You could throw an exception if the parameters aren't valid but that wouldn't get round this problem. You could make the Sub new private (or protected) and provide a shared public sub that accepts the parameters and does the validation - if everything's fine it creates and returns a valid instance, if not it returns nothing. e.g. Public Class TestClass Private X, Y As Integer Private Sub New(ByVal i As Integer, ByVal j As Integer) X = i Y = j End Sub Public Shared Function CreateTest(ByVal i As Integer, ByVal j As Integer) As TestClass If i < j Then 'Do your validation Dim tmp As New TestClass(i, j) Return tmp Else Return Nothing End If End Function End Class this can be called like Dim t As New TestClass 'invalid Dim t1 As TestClass t1 = TestClass.CreateTest(1, 2) 'valid instance returned Dim t2 As TestClass t2 = TestClass.CreateTest(2, 1) 'nothing is returned Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Kurt Posted January 29, 2004 Author Posted January 29, 2004 I thought shared (static) methodes only could use other static members. The constructor must be an exception then, or is actually always static from nature. Logical enough, otherwise an instance would be needed to create an instance... Quote qrt
Administrators PlausiblyDamp Posted January 29, 2004 Administrators Posted January 29, 2004 It's not directly accessing a non-shared member though - it's creating a new instance, which calls the new instance's constructor as normal. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.