Results 1 to 8 of 8

Thread: Why we use Constructor in C#

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    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....

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,930

    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).

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    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?

  4. #4
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,600

    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?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  5. #5
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,600

    Re: Why we use Constructor in C#

    Quote Originally Posted by colrh View Post
    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.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  6. #6
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    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.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    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

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    May 2016
    Posts
    157

    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
  •  



Click Here to Expand Forum to Full Width