none
C# Constructor RRS feed

  • Question

  • I am trying to understand the purpose or reason for constructors, beyond the definition and more of why they exist - what value to the provide.  I feel like I have a bunch of information and definitions, but I am struggling to put all the pieces together - like how data flows from the application to the class and back.

    Here is what I believe to be true:

    You create a class to group information and activity of related things together.  For example, the automobile class.  So I create the automobile class:

    class automobile {}, then I add member variables to the class:

         class automobile

         {

         private string make;

         private string model;

         private int year;

         }

    OK, so far I am ok.  But when the conversation of constructors comes up, things start to get fuzzy.  I have seen quite a few definitions for constructors - "a special type of methods that are executed when an object is created", "constructors initialize the member variables of a class", "you need at least one constructor".

    In as much as that is understandable, I don't get what it means exactly.  Why is that important?  What value does that bring?  What does it all mean exactly?  How does the data flow?

    I have this class - with no constructor (yet), and I think I have seen some explanations that a constructor is automatically created when you create the class, but I don't see one.  So I create one, and then I ask myself if I am writing code I don't need to write.

    How do I access the constructor?  Or do I even need to?  How do I communicate between the application and the class?  I have seen that process when using a console application, but when I have tried to create a Windows Form application and have information displayed to a label, I can't see to connect what is in the class to the application.

    And how do methods differ from variables?  I feel like I am close to understanding yet still totally in the dark because a few pieces are wrong or missing. 

    I have reviewed the q/a about constructors and I still feel like I don't know anything.  

    Tuesday, January 16, 2018 11:23 PM

Answers

  • You have the same casing in the accessors' bodies as for their names, so they are calling themselves endlessly.

            public string clubName 
            {
                get { return this.ClubName; } // Capital "C".
                set { this.ClubName = value; } // Capital "C".
            }
    
            public int clubDistance
            {
                get { return this.ClubDistance; } // Capital "C".
                set { this.ClubDistance = value; } // Capital "C".
            }

    And by the way, the convention is the other way around - the public accessor should start with a capital letter, the private variable it uses should start with lower case.


    Edit : I used the wrong word. I meant property, not accessor. I was getting mixed up with another language.
    • Marked as answer by tddyballgm Wednesday, January 17, 2018 5:27 AM
    • Edited by Ante Meridian Wednesday, January 17, 2018 5:27 AM Not accessor, property.
    Wednesday, January 17, 2018 5:17 AM

All replies

  • Greetings tddyballgm.

    That's rather a lot of questions, so I'm not sure where to begin with answers, but I'm going to have a shot.

    A constructor is something you invoke when you (jargon alert) "instantiate" a class. That is, when you create an instance of that class using the keyword "new". Lets look at your automobile class as an example, with some modifications.

    // By convention, a class name should start with a capital letter.
    public class Automobile
    {
       // Let's make the properties (variables) public so other classes can access them.
       // And because they're public, convention says they should start with caps as well.
       public string Make{get; set;}
       public string Model{get; set;}
       public int Year{get; set;}
    
       // Here's a constructor which initialises all the properties. 
       public Automobile(string make, string model, int year)
       {
          Make = make;
          Model = model;
          Year = year;
       }
    }

    Now, suppose that somewhere in our code, we want to create and use a 1990 Ford Focus. We can do it in one step, thus.

    Automobile FordFocus1990 = new Automobile("Ford", "Focus", 1990);

    If we didn't write the constructor, we would have to make do with the default constructor (which you can't see). This would initialise all the properties to null or zero (depending on the data type). Creating the same type of car would then go something like so.

    Automobile FordFocus1990 = new Automobile();
    FordFocus1990.Make = "Ford";
    FordFocus1990.Model = "Focus";
    FordFocus1990.Year = 1990;

    Which is a lot more cumbersome. It also means that outside code is setting properties, rather than the object itself setting it's own properties (this might sound unimportant, but it's frowned upon by Object Oriented Programming Nazies).

    Does that help so far?




    • Edited by Ante Meridian Wednesday, January 17, 2018 12:23 AM Typo.
    Wednesday, January 17, 2018 12:19 AM
  • Hello,

     There is not a simple answer to your post. However, what I think you are trying

    to understand about C#, or other programming languages, is Syntax. Syntax is

    the rules that govern the programming languages as Grammar does English.

     

     Not sure if I can help explain usage any better than MSDN Docs. So if you can

    direct your query to a single specific topic then I am more than glad to assist.

     

    Thanks :)

    Wednesday, January 17, 2018 12:26 AM
  • Hello tddyballgm,

    >>I don't get what it means exactly.  Why is that important?  What value does that bring?  What does it all mean exactly?  How does the data flow?

    Constructor, as the name suggests is to construct an instance, what does mean the instance, it just is some data structures existed in your memory. How to create these data structures? In C#, the rule is "new" keywords + constructor.

    automobile au = new automobile();

    When you talk about the constructor, it usually accompany with the "new" keywords. what does the "new" job? The following is a process that create a instance for reference object.

    1.Open the physical space in the heap memory.

    2.Fields is allocated with space and assign default initialization.

    3.Fields begin to be assigned explicitly.

    4.Init the entity's construction code block and invoke the constructor.

    And you could get detailed info about ctor syntax here. Hope above would be helpful.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, January 17, 2018 2:23 AM
    Moderator
  • Ante,

    That does help, thank you. 

    Let me see if I get this: If we don't create the constructor, we have to write out the five  lines of code (FordFocus1990.Make = "Ford"; etc.)each time, but because we have created the constructor, the constructor, and thus the class, know which each 'thing' is when using the one line of code.  As long as the data types match, you can put the items in order of the ctor.

    What do you mean by the "outside code is setting properties, rather than the object itself setting it's own properties"?

    I think things are getting closer, but when I try to create a class, instantiate it and pass the constructor data, everything seems to look correct, but I can't get the information to display to a label (I am trying this in Windows Form).  I can run a test and get 'test' to display, but I can't figure out how to display all or some of the class information to display.  It's like I can't complete the process.

    • Edited by tddyballgm Wednesday, January 17, 2018 4:44 AM
    Wednesday, January 17, 2018 4:02 AM
  • Fei,

    Awesome, I love the numeric ordering of the information!  It helps me to think of each step along the way, and knowing which step has to come before another.

    Thank you!


    • Edited by tddyballgm Wednesday, January 17, 2018 4:05 AM
    Wednesday, January 17, 2018 4:04 AM
  • The idea of classes is that each object is responsible for its own data and methods. The outside world (usually other classes) should not be able to tamper with the internal workings of an object. So object1 can instruct object2 to change its data, but can't directly change object2's data itself.

    Actually, I should not have mentioned this concept to a beginner, because it's confusing. It's one of those things where you will see lots of cases where it appears to be violated but there are technical loopholes that mean it isn't. And explaining all the details here would take far too long and just distract you from more immediate concerns. Forget I mentioned it.

    As for the example above, I think you have the general idea. Just bear in mind that it's a very simple example, and constructors can be a lot more complicated than that. They can do anything that any method can do, but are usually reserved for initialisation, and that initialisation can take the form of more than just setting a few variables that are passed in.

    For example, a particular class might need to read data that it needs from a file (say, a Library might need to read a list of every Book it contains). You could call the read method in the constructor, so that you know every time you create an instance of the class the read will automatically be done and you won't have to remember to do it separately.

    Wednesday, January 17, 2018 4:42 AM
  • I tried to create a Windows Form application, where I would use a class and ctors to display information to a label.  As I look at everything, I think it should work, but it freezes.  When I remove any reference to the class and/or ctor, I can display a text message saying "Test", but if I try to get the data to display, it freezes.  Here is what I tried to create:

             

     class GolfClub
        {
            private string ClubName;
            private int ClubDistance;

            public GolfClub(string clubName, int clubDistance)
            {
                ClubName = clubName;
                ClubDistance = clubDistance;
            }

            public string clubName 
            {
                get { return this.clubName; }
                set { this.clubName = value; }
            }

            public int clubDistance
            {
                get { return this.clubDistance; }
                set { this.clubDistance = value; }
            }
        }

    (Here is where I try to send data to the class via the ctor and get the data back, but I can't get it to work)

     public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void btnClubInfo_Click(object sender, EventArgs e)
            {
                GolfClub club = new GolfClub("Driver", 300);
                lblClubInfo.Text = club.clubName;
            }

        }

    I have tried multiple ways to get the club info to display to the label, but no matter what combination I try, I seem to go into an endless loop.  Can you see and explain where I am going wrong?

    Wednesday, January 17, 2018 5:10 AM
  • You have the same casing in the accessors' bodies as for their names, so they are calling themselves endlessly.

            public string clubName 
            {
                get { return this.ClubName; } // Capital "C".
                set { this.ClubName = value; } // Capital "C".
            }
    
            public int clubDistance
            {
                get { return this.ClubDistance; } // Capital "C".
                set { this.ClubDistance = value; } // Capital "C".
            }

    And by the way, the convention is the other way around - the public accessor should start with a capital letter, the private variable it uses should start with lower case.


    Edit : I used the wrong word. I meant property, not accessor. I was getting mixed up with another language.
    • Marked as answer by tddyballgm Wednesday, January 17, 2018 5:27 AM
    • Edited by Ante Meridian Wednesday, January 17, 2018 5:27 AM Not accessor, property.
    Wednesday, January 17, 2018 5:17 AM
  • Start with something simple. For something very simple such as:

    int i;

    If you do that then C# complains that it is not initialized. So you do:

    int i = 47;

    And C# is happy.  Now constructors are only relevant to classes but the moving of the value 47 would be the constructor if there was one. When the object is more complicated more stuff needs to be done and that might even require memory to be allocated; there are many possibilities. The concept of constructors is so obvious to those of us familiar with them that probably most people think it would insult others if they explained it. Sometimes it is difficult to know when to explain the basics because if the person does not need it then they might resent getting the explanation.

    I know that some of us learn differently. I have never seen a book that teaches the way I can learn best. When I was in High School I was frustrated that teachers just dump out a bunch of details. I can learn better with concepts and it seems that many people, and all teachers and authors, cannot do that. So I am not criticizing you for being different.



    Sam Hobbs
    SimpleSamples.Info

    Wednesday, January 17, 2018 5:27 AM
  • Such a simple thing, yet caused a huge issue.  Thanks!! 

    These are the fine points I mess up on.

    I greatly appreciate your help.

    Wednesday, January 17, 2018 5:27 AM
  • No worries.

    Please check out my edit of my last post. I should have used the word "property" instead of "accessor". It's important to get the jargon right in order to avoid confusion when reading manuals or conversing with other developers. Sorry about that.

    Wednesday, January 17, 2018 5:37 AM