-
Feb 7th, 2022, 08:01 AM
#1
Thread Starter
Addicted Member
Why we use Constructor in C#
Hi.
Once again thanks for guiding me in this thread and referring me to the website from where I started to learn C#.
I've reached to OOP concepts in C#, where I am little confuse with Constructor.
Apart from this learning tutorial (mentioned above) I've gone through different forums, googling different articles about Constructor. The only thing I got that:
"A Constructor is a Special Member Function which is used to initialize data members......"
Question:
If constructor is using only for initializing values, so why don't I use pre-defined values?
Ok if pre-defined values are fixed ones so instead of this I can use simply a function and call it and it will initialize my data members etc. Possible Right?
Then I have to work with Constructor?
And, If as a programmer (new one) someone asks me that why you used Constructor? So what will be my answer? Just to initialize.....?
My understanding over OOP is very small, as I"m just going through OOP now, but its this one is not being picked by me?
I've even read real life examples in different forums, but didn't get at all.
Please guide me....
-
Feb 7th, 2022, 08:07 AM
#2
Re: Why we use Constructor in C#
It is just to initialize things.
The reason for using it rather than your own function is that it is called automatically (you don't need to know anything about the class, you can just trust that the class will automatically configure itself).
If you want to you could call your own function from the constructor, and that is sometimes a good idea because it allows you to easily "reset" the class later if you want to (usually you don't).
-
Feb 7th, 2022, 08:21 AM
#3
Thread Starter
Addicted Member
Re: Why we use Constructor in C#
I've taken this example from docs.Microsoft
Code:
public class Person
{
private string last;
private string first;
public Person(string lastName, string firstName)
{
last = lastName;
first = firstName;
}
// Remaining implementation of Person class.
}
Can't I initialize these data members at first place?
Then why using Constructor?
-
Feb 7th, 2022, 08:37 AM
#4
Re: Why we use Constructor in C#
Ok. Take a step back and think about what an object is. An object is basically a thing and like any real world thing, it has a state. What is a state? Basically it's state is whatever values it's internal fields have. Again, think of a real world thing like say a car. A car can in an off state where it's engine is off. The gear that's currently engaged would also be a state like park or reverse. Let's look at what this would look like in code:-
Code:
public class Car
{
public bool CarIsOn { get; set; }
public string CurrentGear { get; set; }
}
Now here's the thing. Any object, whether it's a real world thing or a programming object has to be created at some point. So the question becomes, what would it's state be after it's created? Well using our example above we could do this:-
Code:
Car myCar=new Car();
myCar.CarIsOn = false;
myCar.CurrentGear = "Park";
The above creates a new Car object and then it sets it state. The car is off and the parking gear is engaged. The problem here is that if we want every car to have this state every time we create a Car object, we also have to make sure to set it's initial state with those two extra lines of code. What if we forget to do this? What state would the Car object be in then? This is where constructors come in. You can use the constructor to set the initial state of every Car upon it's creation from within the object itself:-
Code:
public class Car
{
//Constructor
public Car()
{
this.CarIsOn = false;
this.CurrentGear = "Park";
}
public bool CarIsOn { get; set; }
public string CurrentGear { get; set; }
}
Now we do not have to remember to set the initial state every time we create a new Car object. We can just do this:-
Code:
Car myCar=new Car();
And now we can always be certain that the Car object would have the initial state we want. We do not have to explicitly set it every time. The Car itself would be responsible for it's initial state through it's constructor.
Does this clear things up?
-
Feb 7th, 2022, 08:40 AM
#5
Re: Why we use Constructor in C#
Originally Posted by colrh
I've taken this example from docs.Microsoft
Code:
public class Person
{
private string last;
private string first;
public Person(string lastName, string firstName)
{
last = lastName;
first = firstName;
}
// Remaining implementation of Person class.
}
Can't I initialize these data members at first place?
Then why using Constructor?
In this case the constructor is there to make sure you initialize the object's state. It makes sure that you cannot just create a Person object without a first and last name.
-
Feb 7th, 2022, 09:04 AM
#6
Re: Why we use Constructor in C#
It is not a C# only world - classes have constructors.
In VB - it's a SUB NEW().
And you can have several - with different signatures. And then be able to create your class in a variety of ways!
I have two SUB NEW() functions below. The first one is what a DBDataReader "normally" has - just a SqlDataReader.
I wanted to pass in an ARRAY of rows of data - and have a DBDataReader "use" that as a source of data. That is the second SUB NEW().
Code:
Public Class acsDataReader
Inherits DbDataReader
Private _doSdr As Boolean = False
Private _sdr As SqlDataReader = Nothing
Private _style As String = ""
Private _names As String = ""
Private _columns As Integer = 0
Private _start As Integer = 0
Private _end As Integer = 0
Private _source As IList(Of Dictionary(Of String, String))
Private _hasRows As Boolean = True
Private _reachEORows As Boolean = False
Private _started As Boolean = False
Private _tableCounter As Integer = -1
Private _rowCounter As Integer = -1
Private _rowData As Dictionary(Of String, String)
Sub New(sdr As SqlDataReader)
_sdr = sdr
_doSdr = True
End Sub
Sub New(strStyle As String, strNames As String, intColumns As Integer, intStart As Integer _
, intEnd As Integer, ilSource As IList(Of Dictionary(Of String, String)))
_style = strStyle
_names = strNames
_columns = intColumns
_start = intStart
_end = intEnd
_source = ilSource
_doSdr = False
_init()
End Sub
Private Sub _init()
_tableCounter = 0
_reachEORows = False
_hasRows = _source.Count > 0
End Sub
Class created in two different ways below. I like this code a real lot - solved a major problem I encountered with elegance. Love .Net!
Code:
Dim adr As acsDataReader = Nothing
If _SetData Then
adr = New acsDataReader(_DataStyle, _DataNames, _ColumnCount, _DataStart, _DataEnd, _DataSource)
Else
adr = New acsDataReader(cmd.ExecuteReader)
End If
Last edited by szlamany; Feb 7th, 2022 at 09:07 AM.
-
Feb 7th, 2022, 11:37 AM
#7
Thread Starter
Addicted Member
Re: Why we use Constructor in C#
@Niya
From your First Post:
Can I take the example of Constructor like this:
If I have multiple textBox and RadioButtons on Form and I want that
1. Every TextBox must have a PlaceHolder to tell user what to enter
2. Similarly For every RadioButton or CheckBox I want to specify a value before it is viewed by the User.
So for these scenarios, I have made these initialization in Constructor and when the form opens up by the user so these values with be initialized automatically.
Is this scenario a right example of Constructor?
Did I understand properly the concept of Constructor?
Thanks
-
Feb 7th, 2022, 11:39 AM
#8
Thread Starter
Addicted Member
Re: Why we use Constructor in C#
@Niya
For you SEcond Post:
Your goodself mentioned that:
It makes sure that you cannot just create a Person object without a first and last name.
Apology for my understanding, But I didnt pick up the meaning of this line?
Could you please rephrase it in simplest words.
Tags for this Thread
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
|