C# Access Modifiers (beyond public and private) - what they are, how to use them, and best practices

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
an access modifier in c-sharp specifies who can see and use a resource your pride from they were the public and private modifiers we use it a lot but did you know there are others in this video I'm going to cover six different access modifiers and when you'd use each we're also gonna discuss why we have the various modifiers and it isn't just about security if you're new to this channel my name is Tim quarry and it's my goal to make learning c-sharp easier this channel is full of videos explain of various parts of c-sharp I also have a website where I provide full courses on c-sharp and sequel now one of the things I encourage is for you to practice what you've learned in a real-world application as of the recording of this video I have two different start to finish courses that do just that and more on their way if you want to see how the various things you learn fit together in a real application check out those courses now let's get started in our example project as with all my recent videos I have uploaded the source code as part of a blog post on a subject be sure to follow link in the description to get the code now what we have here is a really simple application deception to show us how these modifiers work okay so we have a console user interface and we have a demo library the demo library is a class library these are both dotnet and don't have framework I'm sorry and this access modifiers is where we're gonna show off the various levels and so I've created the various levels to start us off so you can see where everything lives alright so if we have the a private demo a private protected demo a protected demo and so on and so forth and notice they renamed refer to what their access modifier is okay so the private demo specifies it's a private method alright so let's talk through each of these modifiers and these are all the ones we're gonna cover today where I talk through each of them and who can see them and who can you to restaurant the very top with private so private is only accessible in the area it was declared so think of this as the curly brace boundary so this private demo was declared inside of these curly braces okay all the way down to here which is the public class access to know therefore the only things that can call the private demo are other items in this class okay so let's demonstrate that so if I were to say well I just create another private private void demo so this is just our our demo caller that's gonna be use to try out various things and I could say private demo knows it show up in intellisense made it too quick for you it shows up an intellisense I can see it I can use it in this method okay so the private demo is accessible to demo now if we came over here to console UI and add a reference to our project demo library that should allow us to in program dot C s view or use some of those things so let's add a user thing up here for using demo library okay so now I should us a demo library instance of it D equals what's called demo equals new demo library demo and it's yelling at me oops it's access model access demo there we go I was reading my using state instead of my or my project name instead so demo dot now notice you don't see that private demo you see these four equals get hash code get type and to string which are part of any object and you see public demo and that's it okay so what that tells us is that we cannot call the private demo method from a different project or from a different assembly so that's the far reaches but let's try this let's create a new class inside of our library itself new class and we'll call this the the calling demo class okay and just for because we don't want to do it look at public but they were I have a private void in here called make demo calls and here we'll try saying access demo dots oops demo equals new access demo and demo dot and notice we still don't have that private demo listed we have a few more so we have our equal to get hash code get type and to string those are part of the standard object but now we have internal demo protected internal demo and public demo so we have those three which programs CS only had one but we still don't have private and that's because private only lives inside these curly braces right here for access demo no one outside that can call private demo directly okay now just to be clear here I said directly because if we know that public demo works okay we've seen public demo here we see public demo over here so if I were to put in public demo a call to private demo that would work because public demo has access to private demo whereas these others do not so it's directly these two programmed at CES in the console UI and also the calling demos class neither of them can access private demo so that's the easy one we've kind of gotten familiar with that but it's one make sure that I cover that so that we start off with a good foundation now let's move on to others okay and I kind of bounced around a little bit I want to keep the the naming close so we have you know private protected and then protect it so I want to keep those close but let's skip down now to the next one I want to cover which is internal so right down here you have internal this one is a little bit broader in scope but you can still think of it kind of like the the private okay so what what internal does is it says instead of my scope being the curly braces I was declared in it says my scope is the entire object I was declared it now you may read of this in documentation as the assembly so that just means is the project okay because a project creates an assembly each project so the the demo library which is a class library creates a dll that's an assembly console ui creates an executable an exe file that's an assembly okay so this right here is the level at which internal can be accessed so for example in the calling demos if iris a demo dot Louis internal demo so this has access to the internal demo because it is inside the same assembly the demo library but if we go over here program CS which is in the console UI if I say demo I do not see internal because internal only works in the demo library now before we get too far forward I want to mention I will come back around and we'll talk about different times your places these might be useful and why you use them overall but I will mention here and there some ideas or some thoughts on what could be used and went and you know so for internal this is for stuff that you want to have in accessible for everybody in your DLL especially it's typically what it is think these is helper methods you know methods that you might want to have in moil in class or available in moil in class but you don't want them exposed outside of your DLL so that's what where you use internal okay so that's internal internal works anywhere inside the same assembly but nothing outside the assembly and let's go to the next the easy one only used a lot where while I'm sure it cover it and that is public so public is accessible everywhere pretty much if it says public any button talk to it so if I got a calling demo and you see that public is one of the options if I go to program dot CS and go a demo here the public demo is accessible here as well so public basically means anybody can talk to me it doesn't matter if you're the same assembly or a different assembly if you reference me you can talk to me so that that's a very very common one for us to do because especially in dll's we want to have expose some methods that other projects can use you know think these is the the common library that every users well they have to have public on them because other things have to use them all right so that's another a pretty simple one so you have public we have internal which is at the assembly level and we have private which is at the declaration level basically this in this case the class now I am talking about methods right now and so it does change a little bit or talk about other things so there are you know you can do private variables and you can do internal variables and all the rest but in this case we're focused primarily on just the the access modifiers and so you know in this case in private I I'm pointing out here it's curly brace level because if I were to declare this privates privates whoops wrong level if I were to declare it up here at this class I'd say private int test that also works the same way as the private method okay the same would be the property so this would be a field or a variable a property you can do events and all the rest so I'm more focused on the modifiers just so we're clear on that how they are applied different obviously pretty much the same way some objects can't have certain modifiers for example an interface you can't have a private anything it's just there is no modifier because it's everything is public so there are some you know some edge cases here but really we're talking about is a modifier itself so let's talk about the last single word modifier we have and that is protected now you probably don't see this a lot and there's a reason for it and the reason for it because we don't typically do a lot of inheritance but this is something has used a lot inheritance so if you see inheritance going out a lot you'll pricey protected so what protected means is that you can access it in this access demo class because that's where is declared so the career aces apply here or in any method inside of a class where you were derived from this class so let's clear that up a little bit so if I were to create a class that's critic class right here and say inherits from access demo okay long name but but that's okay because it's more descriptive of what we're trying to do so we're gonna hear it from access to them okay so now just to be clear here this is protected if I went to calling demo and looked for protected I don't see protected see protected internal that's different so I don't see protected so that's even in the same the same assembly and of course we don't see over here we only saw the public one so it's definite out there but if I create a method now inside my inherit from access to know and I said public void test and I said let's create a protected demo let's call that no problem I can do that now just to show you the other thing I can can't do let's try the internal demo yep I can do that let's try the private demo and no I cannot can do private protected but not private so and of course public would work so protected allows me to call it from the class of declarative okay which would be accessed demo that's the curly brace rule or from any class that inherits from this class so this case this class inherits from access demo so therefore it has then access to call the private methods of access demo I'm sorry the protected methods of access demo that can be really useful when you're talking about building something where you have these little helper methods that you can use in those inherited objects and you don't want to make them public you don't want to make them accessible to anybody outside of the class or the inheriting class okay so if this were employee and this were let us say janitor I'm not sure so janitor probably uses some of the helper methods the employee would use and so it could have access to those if they were protected instead of private okay so think of it as private except to those that I inherit from in which case then they're available as well so a little bit more tricky there but there's definitely some some use cases in inheritance ok so now you have two more and let's talk about both the private protected and private internal let's start with doing is color let's go private protected and this is kind of fun so these modifiers are really neat they allow us to scope things out just how we need so private protected says that it is available in access to know ok if we come over here to calling demo and go here we can see it's not available here so not available in calling demo so won't be available in program dot C s either and let's check over here private protected so it's available here in Harry from access demo so it seems like it's scope the same way but there's a difference here and this is something I didn't show you for protected but I go over it now because it does show the difference let's go to console UI and create a new class and we're gonna call this class inheritance demo and we're going to inherit from access demo we'll have to add our using statement here and we'll add our method demo so private void demo now we can call protected demo which is our method inside of the access demo class that's protected okay which makes sense because we can Herot since we're inheriting from access demo we have access to protected methods but notice what we don't have access to there's no private protected okay we have the difference is that even though we can access over here we can't access over here the difference is which assembly it's in so we can access private protected methods inside the same assembly so demo library but not outside of it so it's private if it's outside the assembly if it's inside the assembly it's protected alright so you see how these different these different boundaries being drawn there's a boundary for each circumstance you need now some of these are really edge cases they're not something to use every day and so I'd encourage you to you know practice these things and try them out so you understand how they work me document them for yourself in your terminology so you can understand them and then keep in the back of your mind but then when you're working on code default the private and then if you need something that's available for anybody make it public but then there's those other cases you have these really surgical precise things you can use to fit the permissions you need so let's get rid of this code since we don't have the ability to access that let's go back over here and look at one last one which is protected internal okay so protected internal is a little bit different let's see we can use and we can talk through a cache show you how it works so if we go over here to calling demo protected internal is available cool so we have access to it from a different class inside a same assembly we know we don't have access to it in program dot C yes okay now if we came over here to inherit some access demo and go protected internal we have access to it here ok now let's go over to inheritance demo and say protected internal we have access to it there as well so you have access to inside a same assembly and also from wherever inherits so basically this is protected inside its own assembly and it is internal inside of any asset any class that inherits from it ok so it's accessible everywhere in demo library and it's accessible inside of inheritance demo class alright so those are the six types public is available everywhere ok then we have the least available which is private which is only inside the same class or object it was declared in then we have protected which is inside of the class it was created or inside of anything it derives from that class so in this case here stairs are protected internal works anywhere inside via same assembly and then we have protected internal which means it works inside of this dental library assembly and wherever inherits from so in this case inheritance demo and we have private protected which is only available inside the class that declared it as well as from a class inherits from it but only in the same assembly okay so there's our map all the six different types of modifiers now here's my my personal view and what I have seen typically the most common as you probably know or public and private public because we have these you know these libraries that other object her projects need to call therefore we have public methods so they can call it so programmed ICS can say run this method okay so that's public as we use a lot we use private a lot so you can we can make a helper method or something small that wouldn't necessarily use outside of this the class worth using it so for example let's just actually make this work so we can you are the air I might have here a private static void say hello method that just says hello user okay that would be not say he'll say hello so that money used internally to kind of break up my code have a method do one thing so I can use it more than once I might say hello more than once but only reuse it in this class it's not really useful outside this class therefore private so those two the most common but the one I see not used but I think should be used a lot more is internal so the reason for internal is for a class library especially ok and for helper methods or methods that are common across more than one class so think of this in terms of dry don't repeat yourself and I use dry an awful lot because it's one of the most simple and yet most powerful things a developer needs to learn is not to repeat yourself and so if you rain a same code one once you should probably think about creating some sort of method or something to allow you to use it more than one time but only have it written once so this case if we had the internal demo maybe this is code that everybody uses ok let's just think of it as a calculation maybe it's a calculation we have to use in multiple classes think add ok well I only want to write at once maybe I create a helper class and put in there the add method and make it internal because console UI doesn't need to see it ok but it's helpful for two or more classes inside of demo library so therefore we're not clogging up our our publicly exposed methods but we have a helper available inside all of demo library that's the one I think that people miss often it's the one that you just kind of overlooked and so what happens is they say oh man I need to have as add method in two different classes well I don't make it public because that makes no sense to have this add method hanging out there therefore make it private and just copy and paste it that's you know red flag should be going off somewhere okay that's a much more common use for internal now protected if you're doing class inheritance which isn't nearly as common as people think it would be in audit oriented language but if you're doing inheritance then protected is a very common one because it allows it again to use those helper methods in other inherited classes the other two the combination one's private protected and protected internal these two are more like the mixes I mean obviously they say protected internal it's two different things so they're mixes that help us cover some edge cases where many want to have as helper method available inherited classes and you want to have available inside the demo library assembly well that would be from protector before protected internal okay protected internal covers that we can access it anywhere in demo library and anything else inherits from the class that was declared in that's kind of useful sometimes again small cases but put it in your library of things to use when necessary because you might be tempted to repeat yourself where you have in an internal helper method you go OOP I actually want to have access to it from inside this but it's inside console so let's recreate it again warning flags think about changing your modifiers okay protect it a prior protected prior protected is more about protecting things and make sense right protected protecting things and go outside a boundary of your assembly there's some methods that you create that just shouldn't go outside of your your DLL or whatever you're creating and so some of those things might be things where they do part of a job okay a method should have one job but in the real world a job is really a bunch of jobs put together okay a pretty simple one you go to a bank and you you give a cheque to the cashier and say I would like this cashed well let's put my account put this cheque in my account well they don't just do one task there what they're doing is they're contacting the other bank and they're saying do you have the funds for this if you do transfer them out of this account and then they're transferring those funds into your account now that's a bunch of tasks put together as one larger task so imagine for a minute that you had a method called deposit funds okay it has one thing it puts money into an account so you passing an account number and amount and it puts that amount in the account number that's great and that can be really useful in more than one spot in our assembly our demo library but imagine for a minute if I had access to it at program CS well I could say hey you know what let's deposit funds 56 dollars maybe I'm thinking I'm depositing a check but the reality is I never withdrew funds which is part of that larger task I never withdrew funds or somewhere else I just created that money and put my account which sounds great but you have to have withdrawal somewhere else so those those little helper methods are great and they are self-contained so that you can use them in different ways but you really can't use them independently and that's where you went wide across the demo library boundary you want to say yes it's great to use internally but you can't just have it available for anybody to call directly okay we even was not malicious accidentally calling that method instead a larger deposit check method let's say previously deposit funds instead of deposit check which may sounds very similar but deposit check is the larger task that breaks down in different pieces deposit funds is just the one little piece that's putting money into an account okay so that's why I'd want to have that private protected method so that kind of brings up or kind of starts touching on why do we have these different access modifiers why isn't everything public ok let's talk about that so the first reason why we don't just have everything public and available is so we can protect private information let's just say for a minute that's and let's create a credit bad class my call bad class because don't do this okay so a bad class and I'm like the class public so you can see it and we're gonna make everything in here public let's make it property first nope let's make a and a property nope first we made a variable public string SSN social security number okay if you're outside a u.s. social security number is the government-issued ID that each US citizen gets that's we have to keep private because let's being easier instead of you trying explain social security Mazon why they're a mess credit card number think everybody probably great card number that's a private thing we don't want to expose that well I have made it public so if I were in my main here I could say bad class bad equals new bad class I could say bad dot credit-card number and get that okay that's a security risk same with social security numbers same with other private information typically instead of doing this what we would do is we'd make a full prop prop full and we'd say it's a string let's call it social security over for this one SSN and instead of returning the full social security number like so we would return a partial well I just made a spoof this for now star star star - star star - one two three four okay that's what I do you take this number it cut off the last four numbers and put that there and put stars the previous ones okay so it's storing the actual social security number but it's only giving you back partial sending the credit card number we shall last three or Flast four numbers we don't show the previous twelve okay that's the right way of doing it but if everything is public then it wouldn't matter that this is trying to filter out certain data and not show it think our report or something like that instead if we either accidentally or intentionally said let's whoops not can there we go if we said underscore SSN instead of SSN both of those look about right and they actually both hold a social security number it's just that this one will give you back or display only the last four digits this one will display all the digits okay bad good that's access modifiers okay so that's one thing now I think I've also covered already that securing private methods is a good thing or the security of private methods things like to pop the deposit funds method we talked about or delete user that's a great method to have delete user in a certain context but there's larger picture we think about maybe that's just one step in the process of taking an employee out of the system they've left and so yes we delete the user from the actor directory but we also have to remove make sure you have their keys make sure that have their exit interview and all the rest of things that have to happen as part of a larger task of you know leaving employee or something like that fired employee whatever it is delete user is useful in both of those situations where the leaving are being fired but it's not good on its own okay so that's again security for those private methods now that also brings up another thing which is close or similar but different and that is it prevents bugs okay these access modifiers prevent bugs so let's just think we have a method called create Active Directory employee well that's great but it did it also given the permissions they need no that's a different method but because we created their Active Directory account it looks like we have done the whole job but that was one little piece and so now you have a bug we have a user with no permissions and they come back to us and say ah I can't login as I can't do that well that's because we called the wrong method okay another one let's just say in our bad class we had a another prop oops there we go so this is gonna be the age property now when we set an age we're not gonna worry good citizens and not allow any age we're going to say that's control X here if value is greater than or equal to zero and value is less than let's go with a hundred and thirty then set the value okay so that way we only set the age value if they have a valid H okay now yes zero is a valid age think of a newborn they're not one yet okay they're zero we just don't call them zero 130 I don't think anyone's lived that long I think 120 s somewhere is where any modern person is lived I don't know about historical records but but that's pretty much right so that range it's pretty good okay that'd be that's a close approximation but if I come back over here program that CS whoops let's make it public because by default it's private Microsoft trying to help us out and we're defying their their wishes okay so when I do bad I can do bad either age the property which is good so I can say bad age equals 150 that would work but it would not put 150 into age okay so it's good do nothing essentially but bad dot age equals 150 that will put 150 in the age property is this as a private backing field well I call it private backhand field it's actually now the public backing field you should never have public backing fields okay so this would quote unquote work but it's not supposed to introduce a bug into our system its bypassed our checks for valid data and just put did it in anyways okay so that's a problem now the other thing that these modifiers allow us to do is it reduce it they reduce the confusion and they reduce the options available to us pass similar concepts they're reducing the confusion and reducing the number of options we have when calling these outside of the class so let's look at access to element and cup here to our demo and let's look at what we have access to so now we got a whole list here because it's Microsoft but I can say private demo let's just say demo and let's look at that's not got a filter bite we can say public demo we can see say privates protected we can say internal internal demo it might be even easier if we get something like this access to no demo equals new I'm actually declaring inside itself demo dot notice all the options we have there we go much better so you've access to of course this method we can ignore that and these three you can ignore then internal ignore clone private private protected protected protected internal and public okay and of course to string as part of the standard so we have access to a lot of things and that's just with this little demo however if I go over to program dot CS and iris a demo dot I have my four standard and then my one option that's pretty clear to understand which ones I can call just public demo I don't have the problem of which age to call I don't have a problem of is this part or the whole I just have one option public demo okay now obviously have more than that but it'll only be the options that you really should and can use so while security is important and you should always be giving the least amount of permissions or visibility to your objects as possible one of the benefits the big benefit that people often overlook is that it cleans up for us our our instances so demo dot only has the public things when you're inside of calling demo you only have access to things that are protected internal internal or public ok look larger that's okay because you can use those there for you to use what it doesn't include is the private stuff the stuff that's only you know is set to private the only access demo can use and some of the other things so this not only protects our code it protects our data from security breaches or from bugs or things like that it also makes our code less confusing and it provides us with just what we need to do our jobs and now a ton extra this is really important when it comes to creating a full library now this is a sample library it's for a little application but think about a library for a company a larger company that has hundreds and thousands of methods you really only want to have accessible to you the things you should be able to use because if they expose their helper methods and their private methods and the things that are just kind of one-offs or things like that they expose all that you would have tens of thousands or hundreds of thousands of things that look through that probably aren't named the greatest either so by using these access modifiers correctly you also make your job and the next person along the line make their job as well easier so to review make things as private as possible not the modifier but the the overall intent ok so keep things as small a window as possible and these right here will allow you to dial it in to exactly where it needs to be private for a thing you only want to have access to in this the st. the class is declared public for anything you want to have available outside but then the other ones will modify things appropriately to hit that middle balance in between okay I hope you found this useful I hope you found it clarifying maybe of some of the things maybe you missed you know as you grew up in development or as you improve your knowledge of development maybe you missed why use all these different map modifiers my suggestion for you this is my suggestion for any time you learn something is that you build three to five projects separate projects that you kind of recreate every time but little test projects that try out these different access modifiers don't just use my code create your own weave create your own not only allows you to test we have learned it also allows you to get more experience creating projects and wiring things up and doing references and using statements and all the rest of stuff that you're just not going to get a benefit of if you just get a little bit lazy and use this the pre develop stuff is what happens is down the road you have to be for yourself and you don't have that depth of practice doing it so practice three to five projects or so where you're trying out these different levels of security once you can't understand and use them and go yeah okay I got that then start looking through your code and say is there modifiers I need a change or and it's even better is their code I can refactor that will allow me to become more dry by not repeating myself here where I could use an access modifier may internal that's a really popular one for refactoring but we're gonna use this access modifier to to scope this you know such a way that's available where it needs to be and not where it's not okay so give it a shot let me know in the comments if you have any questions about these modifiers or how your your practice went okay until then have a great day and I am Tim quarry [Music] you [Music]
Info
Channel: IAmTimCorey
Views: 122,194
Rating: undefined out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, course, training, how to, tim corey, C# course, C# training, C# tutorial, public, private, internal, protected, protected internal, private protected, c# access modifiers, c# assessors, access modifiers in c#, c# security tutorial, C# security levels, c# demo, c# source code
Id: jcn5uCZAk2w
Channel Id: undefined
Length: 46min 57sec (2817 seconds)
Published: Mon Jul 23 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.