-
May 7th, 2018, 09:44 AM
#1
Thread Starter
Frenzied Member
parametrized constructor & copy constructor
hi friends,
can anyone tell me ? . why and where we use copy and parametrized constructor in vb.net . and the schenario where is no way . rather than using only copy and parametrized constuctor . any help would be highly appreciated .
-
May 7th, 2018, 10:32 AM
#2
Re: parametrized constructor & copy constructor
Are you sure you're taking a VB .NET course? We don't have "copy constructors" as a formal concept in VB .NET.
But there's sort of an answer, and informally you can make something that looks like a C++ copy constructor and it serves the same function.
We make objects to associate logical bits of data and operations that can be performed on it. (Some argue that should be 'or' instead of 'and'.) Usually data is represented by properties, and actions are represented by methods.
One of the 'jobs' of an object is ensuring the data is valid. For example, if we have a Customer object, it probably has a Name property of type String. If that Name is blank or empty, the customer is invalid. So we can try to set up the property to have a default value, but there will be a brief moment after the object is created when it doesn't really have a Name, and we might forget to set it.
We use a parameterized constructor when we feel like we need some basic data to create an object at all. If you don't use a parameterized constructor, you have to remember to set those properties.
A 'copy constructor' is a C++ concept. The idea is it's a parameterized constructor that takes the same object as a parameter. It's called when C++ needs to make a copy of an object, which can be very frequently. .NET doesn't do this as frequently so it's not a built-in feature. But sometimes you want to make sure one object can't impact another and this allows it. (In .NET, some people prefer to call this process 'cloning'.)
So, practical example.
This is a type with a parameterized constructor that ensures the Name property can NEVER be Nothing and has a copy constructor:
Code:
Public Class Customer
Private _name As String
Public ReadOnly Property Name
Get
Return _name
Set
End Property
Public Sub New(ByVal name As String)
If name Is Nothing Then
Throw New ArgumentNullException("name", "Name cannot be null.")
End If
_name = name
End Sub
Public Sub New(ByVal other As Customer)
_name = other.Name
End Sub
End Class
This answer is wrong. You should be using TableAdapter and Dictionaries instead.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|