C# Constructors Tutorial | Mosh

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay we got two constructors what is a constructor a constructor is a method that is called when an instance of a class is created why do we need a constructor the intention is to put an object in an earlier state that is to initialize some of the fields in the class here is how we declare a constructor so as you see we have a class called customer and this class has a constructor as you see here a constructor has the exact same name as the class and that's a requirement if you change this name the compiler or the runtime will not treat these as a constructor also note that constructors unlike other methods do not have a return type not even void here in this method we can do any kind of initialization that is required note that we don't always have to use a constructor but if we need to initialize an object upon creation that's where we put our code in this example we have what we call a parameter less or a default constructor so this constructor has no parameters if you don't define a default or parameterless constructor for your class the c-sharp compiler creates one freight you're not gonna see it but it will be in the il or intermediate language code that will be result of the compilation that constructor it doesn't do anything it just initializes the fields of the class to their default values what are those default values for any kind of numbers it sets them to zero or boolean types sets them to false or any other kind of reference types like strings or any other objects sets them to know and for characters sets them to an empty character here is another example of a constructor this example we have a parameter here so we get the name of the customer and we set a name field as you see here not the user of the disc keyword this is a keyword that references the current object why do we need that here look here we have two identifiers that look very similar we have this name field in the class and it's named parameter in the constructor of this class they both have the same spell but are using different naming conventions this parameter here is using camelcase so the first letter of the first word is lowercase the name field here is using Pascal case so the first letter of the first word is uppercase it is possible that sometimes we make a mistake and in the assignment operator here we put the wrong variable on the wrong side of the equation in this example we are passing his name here and we simply copy that to this name field here and that's the right way to do it but imagine what it would look like if it was the other way around it wouldn't make sense that's why we used it this keyword here to make sure what we have on the left side of the assignment operator is a member of the class in this case the name field here so what we get from the outside which is in this case the constructor parameter will be copied to the name field okay with that constructor when we create a new instance of customer we can supply a name here at this point the constructor will be called and the string that is passed here will be copied to the name field we have a concept called constructor overloading overloading means having a method by the same name but different signatures what do I mean by a method signature a signature is what uniquely identifies a method that is its return type its name and the types and numbers of its parameters in this example here we have three constructors so we have overloaded the constructor for this class each constructor as you see has a different signature so the first one takes no parameters the second one takes one parameter of type string the third one takes one integer and 1 string as parameter note that the names here do not matter but the datatypes for the parameters and the order of them is important so we cannot have two constructors with the exact same signature now you would wonder why do we need to overload constructor z' the reason for that is to make initialization of this class easier sometimes we may know only the name so we may use this constructor when creating an instance of this class sometimes we may know both the ID and the name so we use this one or sometimes we may know neither of these parameters so we may use this constructor here ok let's start coding and see constructors in action okay let's start by creating a customer class so public class customer now we declare a field public integer ID and another one public string name I need to clarify something here in the real world applications we do not declare fields with the public access modifier as you see here this is just because I want to take things in a step-by-step fashion when we get to the lecture about properties you will see a better way to declare fields for now let's just keep things simple and learn everything in a step-by-step fashion okay now let's put this customer class in a separate file here I'm using resharper if you don't have resharper I highly recommend you to purchase a license for it because it really helps you with your coding note that I'm not a resharpen affiliate and I don't get a penny from promoting their product I just believe resharper takes coding to the next level it makes it much easier and much faster alright let's put this class in a separate file so I put the cursor here and note this little icon here that is used for refactoring that means changing the structure of the code without changing its functionality so here I press alt' + enter' and it pops up this context menu here the first item says move to another file to match type name so I just press Enter I know that now we have a separate file called customer that's es and this file is added to solution Explorer so if I didn't have resharper I had to go here right click and then go to add and I know you don't see that here in the screen so I put the solution Explorer to the left side okay so right-click bad new item or class which would open up this dialog box here and then here we had to type customer that's es it's really not a good and fast way because as a professional programmer you don't want to switch to Mouse while you're coding you should learn to do everything the keyboard that's much easier and faster so let's not worry about creating a new file and use resharper from now on I put this solution Explorer back to where it was there you go all right now let's go to the programs yes here in the console application and create a new instance of this customer so customer customer equals new customer or a better way is to use vara instead of customer because note that here we are repeating this customer word twice and that makes the code slightly cluttered so we can just use var here and let the compiler figure out that customer is of type customer so the code looks a little bit cleaner now all right now I want to show you the effect of the default constructor that the c-sharp compiler creates for us note that here in the customer class I did not create a constructor but I told you earlier in this slide that the c-sharp compiler creates one for us so let's see what happens let's display the fields of this customer class on the console so console the right line customer dot ID and console the right line customer that name know that the way I typed council the right line was via what we call a code snippet which is much faster so I didn't type console dot write line I just typed CW and press tab this is what we call a code snippet it's a quick way to write code there are many code snippets in c-sharp and I have explored many of them in my course double your coding speed that you can find on udemy so let's move on for now okay now let's put a breakpoint here we can put a breakpoint using f9 and we run the application in the debug mode using f5 I'm gonna put a watch on the customer object here so customer let's expand this note the default values assigned to these fields here so ID is an integer and the default value for the integers or any other kind of numbers is 0 name is a string and the default value for strings or any other kind of reference types is not so this happened by the default constructor that the c-sharp compiler created for this class okay now let's declare a constructor and see how we can initialize this field upon instantiation of a customer so I stop the debugger using Shift + f5 we her class to do that I simply press ctrl and tap look we got the open windows here in Visual Studio I didn't have to go and grab my mouse go to solution explorer and double-click customer all right now here let's declare a constructor to declare constructor there are two ways the slow way is to type public and the name of the class and the curly braces what is the fast way tor has in short or a constructor and note the icon for the code snippet here so that's a code snippet here we can press the tab there you go we got the constructor so this is how I want you to code I don't want you to type every letter as a fast coder you should know all your shortcuts you should code like a ninja okay now let's give a parameter to this constructor so I go here and let's say integer ID and here we need to copy that to our ID field so I type in this that note here are the members of this class so here's our ID field equals ID now let's overload this constructor so I'm gonna create another one with a different signature I can see tour you got here at this time I want to add two parameters int ID and string name okay now let's initialize them this that ID equals ID this the name equals name now if we go back to our program class again using ctrl + tab here note that we got a red underline and that's because the compiler cannot find a default constructor that is parameterless so we can no longer create a customer object using this constructor because it doesn't exist so what does this mean that means because we created two custom constructors the compiler will no longer create that default or parameterless constructor so if we still want to have this freedom to create a customer object without supplying any parameters upon instantiation we need to go back here and create a default or parameterless constructor so seat or that's it in this case I'm not doing anything here like to program red underline is gone but also when we open the bracket here note that here we have three overloads or the constructor one is without any parameters one takes an integer and one takes an integer and a string let's use the third one i DT 1 and the name to John now we're on the application now that ID is initialized to 1 and name is initialized to John and that's the intention of using constructors you okay now let me tell you a best practice let's get back to our customer class see in this case our customer class has only two fields and we have created different variations of these constructors here for initializing this field what if we had five other fields here would you go and create seven other kinds of constructors or initializing each of these fields no definitely not because that would create a lot of clutter in the class we only use constructors in classes and situations where we really want to initialize an object to an earlier state that is really important for that object to perform in this simple example we have here it doesn't really matter whether the customer object has an ID or not same goes for name we can always create a customer back here let me remove these two parameters we can always create a customer object and then set the ID here it's not the end of the world John but there are cases where you really have to initialize an object to an earlier state what is an example of that let me show you so I want to create a new class let's call it order public class order let's not worry about the fills in this class for now so I'm gonna put this in a separate file put the cursor here Alton enter enter done now go back to the customer and the customer we want to create a list of orders so we use the list class public list of order and we call it orders in case you're not familiar with this list this list is a generic class that takes a parameter this is what we call a generic parameter so it represents a list of objects and this parameter here specifies the type of those objects so in this list we can store objects of type order note that this list is declared in the system that collections the generic namespace and here because I'm using resharper as I was typing list of order resharper automatically added that using statement on the top if you're not using resharper you have to manually add this statement okay let's move on as a rule of thumb and as a best practice whenever you have a class like here and that class has a list of objects of any type always initialize that list to an empty list what I mean by that is in the default constructor here we go and type orders equals new list of orders now you might wonder why I think the best way to explain it is by showing what would happen if we didn't do this so let me just comment this out to do this with resharper you can press ctrl and slash if you're not dissing resharper control C alright let's go back to the program let's add a new order for this customer so I'm gonna create var order equals new order now let's say customer that orders dot add this order if we run the application now it's going to crash we got an exception reference exception the reason this happened was let's close this because orders was not initialized and by default because it's a reference type it was set to null so when we call the add method on a null object we get null reference exception which is a very mad thing it's something we need to avoid at all times now an amateur programmer may solve this problem by doing something like this here so saying order sorry customer that orders equals new list of orders that may look like a solution but it's actually a bad solution in fact I wouldn't even call it a solution it's a hack it's a patch why because here in this main method here we should not be responsible for initializing that orders list to an empty list it's not the responsibility of this class here this class just wants to add an order to this customer is the responsibility of the customer class to make sure that his orders field is initialized to an empty list and it's not a null object if you take this responsibility from this customer class and initialize that orders field somewhere else then it's going to be a problem because everywhere in our code we are going to use a customer object we have to remember to initialize that orders field okay so I'm going to remove this line here and go back to the customer class in the default constructor I want to make sure that the orders field is always initialized to an empty list so that's the rule of thumb whenever you have a class and that class has a list of objects make sure that list is always initialized now we have another problem here if we use this constructor here everything is good the orders field is initialized but what if you use either of these constructors here orders is going to be known well we can go and copy/paste this line into these constructors but it's not really a good way what if we had three other feels here that they all were lists so we had to copy-paste three lines of code into each of these constructors here is there better solution of course there is we can use that this keyword let me show you how it works so here in this constructor upon declaration I would put : this and put the brackets like this this means constructor is being called first is going to call the constructor without parameters so before this line is executed this constructor is going to be called which will initialize the orders field and then we get into this constructor here let me show you another example to make sure we really nail it down so using a similar technique I can go to this constructor and : this note that we have two constructors here now we can call one is the default parameter list constructor one is the one that takes an ID I'm gonna pass this ID that is coming here into this constructor and then get rid of this line here what this means is when we use this constructor to initialize the customer object first it's going to call the constructor that takes the ID parameter so are we gonna go here and note that here before this code is executed we're gonna go here at this point the orders field will be initialized then we get back here the ID will be initialized and finally we'll get back here the name will be initialized so what I want you to learn here is that we can use the disk keyword and specify any of the other constructors we would like to pass the control to now here we have a simple example and it's kind of okay to pass the control from this constructor to this one to this one but in general this is not considered a good practice because it makes the control flow a little bit complicated for example imagine someone else had written disco and you had to maintain it you look at this constructor and then you had to look somewhere else and then you had to look somewhere else it's a little bit ugly so what I suggest to you is keep the using of this in this way to a minimum and only define a constructor when you really have to initialize some fields of your class in this example I explained to you that we really have to initialize this orders field here so we created a default constructor I can argue that these two are really redundant and they're just making the code a little bit ugly and hard to maintain so it's okay to remove them but I'm just gonna keep them here because I wanted you to learn a few concepts here one is the default and parameterless constructor another one is the concept of overloading constructors that means we have three different constructors each has a different signature and how we can use that this keyword to pass the execution to another constructor in this class well that's pretty much it for this lecture I hope you enjoyed it and thank you for watching hi guys ma chere I hope you're having a fantastic day or night wherever you are in the world this tutorial you have been watching is actually part of one of my C sharp courses where you will learn everything about classes interfaces and object-oriented programming in case you're interested to enroll in the full course I've put the link for you in the video description and if not that's perfectly fine have a great day
Info
Channel: Programming with Mosh
Views: 158,344
Rating: undefined out of 5
Keywords: c#, csharp, .net, .net framework, visual studio, oop, object-oriented programming, constructor, programming with mosh, code with mosh
Id: q7aWkjH3UUI
Channel Id: undefined
Length: 23min 23sec (1403 seconds)
Published: Wed Nov 08 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.