Static class vs Singleton in C# | C# Interview Questions & Answers | Static & Singleton in CSharp

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
ready and I hope that I am life I think I'm like right so our first thing good afternoon everyone I can see a lot of people have put the messages on the chat so good afternoon Ashok Rahul Rajesh Ritesh we make the wish Upendra and everyone and and superjet Santosh a lot of people logging in out there so today's session is on our topic you know which is quite discussed you know between the developer community static was a single term and guys let me know if you can hear my voice you know just to check that my voice is seen my voice is audible and my screen is seen out there very quickly so I have this design pattern lectures you know which is there on quest pond and I have been taking design pattern for a very very long time and one of my favorite course which is very near to me is the learn design pattern in eight hours course and whenever I you know whenever this course is there in in quest fond and also I take a lot of trainings and one of the question definitely comes in is that static versus single ton right so before I get into the topic I want from everyone out there that what do you think you know what do you think that is static and singleton pattern both same right if yes what know and so on please go ahead and put down on the chat saying that no shape we feel that static is different some people will say oh like singleton means creating one global object and static does that right so go ahead on the chat and and put down you know that why you think that singleton and static are different or and if you think they are same then why it is right so first thing let us go ahead and let me use Google out here and let us see what exactly this singleton pattern is right so I will not waste time too much singleton pattern what does gang go for talk about the singleton pattern I can go to Wikipedia I think that's the best source at this moment we can take you know as a source to understand right I have avoided PPD's today why because I feel that when I put some definition of PPT out there it is possible that that definition is changed or the definition has my own own thought right so I would prefer to take the Gang of Four definition so here if you see the Gang of Four what they have said is singleton design pattern is this and this and this and let's look at the first statement it restricts the instantiation of a class to one single instance right and this is useful you know when you need one object is needed across the system so basically you want only single instance of a class across your complete project now why do you want a single instance of a class there are many reasons for it like you know first one of the reasons is you want to go and cache some data or probably you want to go and share some global data for example and hit counter must be you want to cache some data like country master and state master you know those kind of data you don't want to hit the database again and again right so such of those scenarios you know where singleton pattern can come to use but now the question is that's where the question is right you know so let us say I have you can see my visual studio out here so let us say I have country object a country class out here let me create a country class right and let me create an ID for a country and a name right so assume that I want to go and cache this country master right so I want to go and cache my master so I want to go and read this data from the database and load it and when we once it should be loaded and then afterwards it should not be loaded again and again so the best way what you can do is you can go ahead and you can create an static object right so you can just say static list of country right and see it's countries is equal to new list of countries and you can go and you can fill this object somewhere in the constructor must be so country country what is that out there okay the semicolon list okay the list is that Drix we need a generic Saudia so fine generics right so in the constructor what I can do is I can go ahead and I can load these countries from the DB right so must be this is null out here right so this is null and new list of countries and we write here the code which can load the data from the DB so now if you see this small code out here does the same thing so if you look at the Wikipedia definition restrict the instantiation of a class to one single instance so definitely the static keyword ensures that one single instance is there not more than that right so that is one on single instance second it is useful when one object is needed to coordinate actions across other objects so basically one single instance and static is doing it right so now let me go back on the chat coming back again so what's the difference between singleton pattern and this static keyword right so let me go back and let us see some of the chat answers out there and then we can decide remember that this session I see it as a more of a discussion session definitely I will be demonstrating I will put down my points out here but at the end of the day you know I I would like to also get upgraded I would like to also know a lot of things from other people right both are different because singleton pattern is the instance based on base but static is not okay so from a J Kumar I can see the message both are different because singleton pattern is an instance definitely but static is not my question is singleton is a pattern it says that one single instance right that J so static does that so do I have to code something extra a very simple question is do I have to do some extra coding for it right now again like from visual we have an answer here singleton is a pattern very good singleton is a pattern and static is a keyword absolutely so let me put that thing out there so singleton is a design pattern that means we need to do some extra coding into it and that is a keyboard again coming to the same question it creates a single instance of an object right visual so the question again is like if it is a pattern then I know that when you say pattern means it we need some code right you have to write some extra cool so what are those extra code which you need to write with static does not have it right I can see some inputs from Rahul here static classes cannot maintain state so Rahul like static is a global object it does maintain State right so if you look at a I have not created here a static class I have created a static object just to correct it so it does maintain state it's a global state right so I did not get that statement such an is saying in static only one li static data okay device yes we have to do some extra coding for singleton singleton can be passed as a parameter right so singleton can be passed as a parameter a JIT so again the same thing the question is that static object can also be passed as a parameter and static object you don't need to really pass as a parameter because it's already global right now so let me go back I can see some discussion out there you know but let us let us try to go to the main thing so I'm going to go back and again switch you know my scenes out here and let me just keep referring the Wikipedia because I feel that so this is the right so so now very quickly first thing when you say that one is that you have to have one global object right so when you talk about a global object so let me go back here and go back to my whiteboard and let us try to visualize so definitely like static is so when you say a global object a single object right the time you create a global object which is shared across your project right you also need to take care of lot of things the first thing you need to take care is that if possible you know we can do lazy loading out right so if you see this Vika pedia very quickly I can just highlight to highlight it out here okay lazy loading right second I would like to really also let me know you can see this Wikipedia has lots of code out there but I don't want to go through all the code we will see the code in c-sharp definitely but let me write so Wikipedia also does not answer it the best right it's so sad right they have not answered it everything I was expecting something out there must be I will go and update the Wikipedia right ok so that is let's see if they have not done anything out there right so fine so let me let me talk here and then I will go back to Wikipedia so first thing is lazy loading for example in static objects what happens is the data is loaded if you need or if you don't need it means the time you say static and if you load it in the constructor let's say you note the country master it is noted it is it is loaded even though if your application does not need it right that's the first thing the second thing is thread safety I think this should have been the first thing I should have discussed right thread safety if this global object is accessed by two threads it should be safe for example in the country collection assume let's say you are loading the country collection you are refreshing some country collection at the same time somebody's accessing it so let's say in the database in the database you have five data and now you have ten countries right the client who will the client who is out there there can be a condition you know where in the countries will be completely null isn't it so we should just have thread safety as well right so if you talk about singleton pattern definitely it will need the static keyword in case at least in c-sharp it will need the static keyword you know to create the single instance but a singleton pattern is equal to the static keyword only helps him to make the object booble so this guy just helps you to make the object global but he does not help it to make it thread safe that's the core unity right he does not help you to make does not help you to implement lazy loading right he does not help you to do n capsulation right or I will say let me put encapsulation right or encapsulated iterator that's a nice word I like it right let me use encapsulation and I will add an extra out there an iterator so that means you know for all these things out here this extra things out here you need to go and write code so the difference between singleton as everyone said yes it is a pattern pattern means there should be some extra coding in it right not just static keyword and also all these things for example now so what I will do here in in normal cases when you see a singleton pattern so you will have a separate class firstly you should have one separate class so for example here I will have a class a static class most probably a static class which will say singleton and this static class will now have country master list it can have on hit counter it can have anything right and you know it should be it should have and everything should be private encapsulated so in other words what I will do is I'll create a private definitely static list of countries so you know like I can also say that it this singleton pattern is a rapper on lot of things my it's a rapper you know which does global object it does thread safety it has iteration it has encapsulation so you can see here now I'm making it private right and I will make it null so you can see the first thing is this is not a naked variable it is not like this think about this this static object out country is out here any developer can go and somewhere make it null think about it if somebody goes and does this you are gone I again repeat this sentence a naked static object out there anybody can go and destroy it anybody can go and manipulate it think about it you have a country master and there is one funny developer out there who is accessing the country master he adds his own country out there or he just for a funny just goes and makes it null I'm not saying fun I know that developers don't do fun like you know but I'm saying must be makes a mistake of doing it null right and once he doesn't allow there it is going to go and affect everyone because this country object is global so the first thing is I feel you know personally that singleton and capsule eights those global objects you know anybody cannot go and just hamper it right and if and second it is lazy loaded so basically I will have a method like this static method list of country get countries so until somebody does not call get countries this underscore countries is not getting loaded so you can see here if underscore countries I'm sorry it's afternoon Sunday afternoon and a DC afternoon so must be Mike I don't have that energy of coding here so you can say new list of countries lazy loading so again one more feature out here on demand loading lazy loading so point number one protected encapsulated point number two lazy loaded right also as I've said that nobody should be able to go and destroy that object for example you can see now this is the list of countries if let us say now let me use our singleton pattern out here so I'll go out here and say I want to access the singleton object but look at the problem so singleton dot I will say get countries but the problem is but the problem is I can go and say add now that is bad right so somebody can go and say add and then somebody can go and see it null who knows you know what kind of things can developers can do so like someone can because all the objects are by ref you know so what someone can do is where countries and he can destroy this country's object and if this country's object is destroyed then your complete global object can shake your system right so the another important point is that it should be implementing iterator if somebody wants to go and browse through this get countries then I would really create and use an iterator pattern so 0.3 safe iteration how do you do a safe iteration I will probably make this as I enumerable when you make it as ienumerable you don't get those manipulative methods nobody none of the developers can really go and say now say dot add you can't do that you can see that you only have the enumerated methods right so this is the third point I would like to see that a singleton pattern should have you know and the most important one let us say if I have a method out here which is for loading these countries let us say someone is going and loading this countries out here somewhere out there you know they are loading this list of countries for instance let us say it's public static void load countries let us say so let us say or refresh countries now whenever you are refreshing the countries you just want that when that refresh is happening and at the same time if someone else is accessing he should not be able to access it isn't it so probably what you'd like to do is when you're loading it you'd like to go and lock the countries and do it so must be you would like to have a lock out here right lock the underscore countries and then do the loading part out here new list of countries right so one more thing which I would like to see out here is point number four thread save thread safety so this is exactly this is thread safety right so either you can use a mutex or either you can use the semaphore please watch my multi-threading videos out on respond so you know just putting down the context out there and many more things guys I am not really aware of I am not aware of that what can be the scenarios where you know a global object can have problems so there can be many more things out there so for me you know singleton is a clasp is a wrapper which also has lots of those extra browning things you know like thread safety and lazy loading and encapsulation and iteration right and the most important part which I feel is this creation of static object you know is a technological thing is in other words somebody can say okay like I will not use static object I will use the asp.net cache object it's okay if you want to use asp.net cache object or someone can use something else you know which is more global out there right so the technical part of making and global object is more of a programming feature programming language feature or the technology like asp.net you know which has cache object objects right but it does not have those extra nuts and bolts you know like thread safety and lazy loading and so on right so I feel that singleton pattern is equal to static plus thread safety plus lazy loading plus encapsulation plus iteration safe iteration and many more things which I am not aware of so if you go to this Wikipedia link out here and if you look at those codes out here for example this is a Java code out here you will see that this is lazy loading so you can see the instance is and if the instance is null then then only loaded or else don't load it we use the lock keyword they have something called as synchronized right and many other things you know which is out here right so when you say singleton out there it's a pattern it has some extra coding right and clearly the pattern definitely says that restricts the instantiation of a class to one single instance but it should not have side effects it should not have thread safety issues it should not have performance issues you know which like you know just to load all the objects even though you don't need it you only have loaded it right so I think you know those things are not given clearly out here on the Wikipedia as well as it is discussed you know but I feel that that is something has to be updated so they have updated the code I can see that everybody codes the singleton pattern in a proper way they create a class you know they make the constructor private they do have all that you know but it is not discussed openly on you know out there are probably not explicitly mentioned that that these are the differences right and also I would like to highlight out here that this singleton is more of an anti-pattern means it is used unnecessarily even though when it is not beneficial for example if you go to any of the interviews out there people just ask you which pattern have you used in your project and he will just say that singleton pattern so it is it is overused or misused or used you know when it is it's not needed at all people have just created static objects and created a mess around it right so I feel that it's definitely an anti-pattern it should be used you know as per the needs of the project you want to do some caching you want to do some performance tuning right and that's why a lot of people say it's an anti-pattern right and remember that global objects whenever you do something you create an global object out there right you are calling for trouble if you have a global object out there that means that everybody is manipulating it and when everybody is manipulating it you can have bugs you can have issues right so let me again go back to Chad let me know that you know this as I said that this is a more of a discussion it's it's not that I want to teach here something you know I just I'm just here to say that what I think is singleton pattern most common use is a logger is it related to dependency injection no petition a singleton pattern does not have any relation to you know the dependency injection it can have an indirect you know but not like a real ordeal it is not that it is not meant for dependency injection right what are the real-world example from the wish so real example the wish I have already said the first one which i think is that you want to do caching you want to load the object once for example a country master or a state master you want to just load it once and then you don't want to load it again and again second examples are like hit counter so you want to just go and do and hit counter as someone has set out here logger object now logger object you need a single instance probably you want to just have a single instance you don't want to create the instance again and again so I again feel that singleton pattern is there right but we use singleton for data based object creation so yeah I did not get that Saru if you can type down more out there right okay so any questions guys so it this is a very small topic and I will just stick to the topic out here and let me iterate you know what I have said first thing must be I can write down on the board and please put down everyone so first point as everyone has said singleton is a pattern but and static is a keyword definitely but it has lot of those things extra which which are needed right like thread safety thread safety lazy loading right encapsulation and lot of other things right second most important again which I've said it is an anti-pattern means people use it unnecessarily you know where it is not needed it is still used it right so must be you should really think about the scenario where where it should use and where you should not use it the third thing is you know the singleton pattern whenever you are we are creating in c-sharp you will definitely need certain keywords out there lock key word for thread safety for lazy loading you can use the lazy keyword as well in case you are not aware of the lazy keyword you can search on this YouTube channel I've talked about the lazy keyword and definitely you know you should use ienumerable so that you have what you call safe iteration people cannot manipulate it right so encapsulation right our fourth one you know which which I feel is is also again important out here is that the use of singleton pattern for data sharing or data caching second data caching and also like you know you have you want to share some global data you know like global chat messages or hit counters you know something in which is more global right and second also you know some of those objects like logger and utility objects rather than creating an instance again and again people just want to use it right but remember to be very careful for example a logger object I probably won't make it lower that is it we can have a discussion on it but think about it a logger object is global out there and let us say at the same time two errors happen so it should it should not overwrite the previous error right both of the error should be logged properly so these are you know some of the nodes you know which I put at the last of the class any questions please put down on the chat yeah yeah thank you Akshay and same to you happy guru Poornima I hope that everybody learns a lot of things yes all right something can be passed two methods while static object as it is and it cannot be passed okay fine oh that's a good thing okay I got it auditing what you're saying okay I got it okay okay fine and that's a good thing what Aditya said I'm sorry you know that I misread it this is again I should put one as a benefit when you create a static object or a static class you can't do those object oriented programming things that is so right you can't really go and do inheritance you can't really go and do you know polymorphism and this is very important point I like Aditya thank you very much you know that's what you know like when you say design pattern we should be discussing you know some of the things I won't remember I think you know if you see one of the implementation you know which is really seen across the industry is that people don't create this using the static keyword you will see people doing like this class single term and they make the constructor private this way that's again a topic you know which is very interesting why do they make the constructor private so basically definitely it is it is having the same thing out here it's means this code is all running if you make a static class let me tell you I you know this is the right way of doing it even if you look at Wikipedia they have not used the word static I'm sure that even if I look at the C sharp implementation they have made the class seal well that's a debatable thing but they are made the class as a normal class and not as a static class and I'll tell you why you know in c-sharp you can see it actually they have given in Wikipedia to implementation thank you very much sealed one with the private and then a static one which I discussed before the class right well I would prefer this version of it you know why because if I have a normal class I can do all those tricks of objectivity programming I can inherit from the class I can do polymorphism I can implement an interface right I'm I'm like you know how do you say God like you know I can do all the object-oriented programming things out there Free Willy right three-strike but when I am into singleton when I am into this static class out there I get restricted with a lot of things suddenly I find I can do this you can now have a private method or you cannot know all the objects should be static and I come into a restriction out there right so I feel that you know creating on class a normal class and doing it helps you to keep that benefits of object-oriented programming out here must be I'll add it out here that basically to create an singleton a best practice would be is that the fifth point is that create a normal class with private constructor right again get this is my thought process out here it's not needed that you know you have to implement it in my project I have seen lot of my team leads you know they make the class of static and I welcome that but if you get those hardliners out there right the design pattern hardliners the architects who don't want to see a single hair here and there must be they would like to see a normal class with the private constructor right so again let me go back to the discussion board out here let me know anything that that's a very good point made there by Aditya yes and sorry I I mistook that statement what you had previously and I have just added more to it what is the disadvantage of singleton so AJ it should be used properly like what is the disadvantage of having a knife nothing but if the knife is used to cut a vegetable it is good but if you start using knife or something nonsense then it is not useful the same way for singleton pattern if you use it for data sharing if you use it for something which is relevant it is always useful it is an anti-pattern or it is the most discussed one because the design pattern is very easy the mentality of developers is that things which are easy a human is that I will say if something is easy out there people talk about it people don't talk don't talk about factory pattern or you know other design patterns because they're tough to understand right so a singleton pattern is is very much talked you know because it is easy people think that you just do static and singleton is done you can clear interviews and the implication is that in projects it is used left and right not thinking about the consequences right so there is no disadvantage of singleton pattern it is just has to be used in the right place okay so so there it's as I've said you know that there are no disadvantages really so thank you very much guys you know this was just the 30 minutes of session today it's not a topic we can elaborate it lot you know but that the topic is very small but I hope that this small discussion has helped you to conclude that static and singleton is four different static is a technical keyword a singleton is a pattern with lot of nuts and bolts and protection right and one special request out here we try to do those these 30 minutes of sessions 40 minutes of session on YouTube right I would suggest you know everyone please go ahead and share this video out let everyone know that you know such kinds of topics are taken on this channel out here and if possible please subscribe to my quest pond website please subscribe to my channel thank you thank you thank you Rajesh Thank You Rahul thank you tin to a Jeff Vikram Amrish nikunj Aditya Aditya thank you very much for the nice sentence I'm sorry you know there was a miscommunication Suraj ignaty and deviation a lot of people who have put down the messages out there happy learning just quickly you know people who are from quest pond out here yesterday night we had a problem there is lot of rains happening in Mumbai and my internet went off and I have two Internet's both of them went off but today we are again connecting a set to zero for zero to zero for we are taking and today my goal is that I am going to go and cover manage identities how to use manage identities with the Azure Active Directory and in connection with the azure API right the azure api and the second one is i am going to go and talk about how to use JWT token so how to implement the JWT token with the seeker perform at between the front end api and the back end a playwright and don't forget on tuesday again people who are quest for members tuesday we are having the data structure screening right so last Tuesday you know we have done some data structure stuff and this Tuesday again last Tuesday we did the Tower of Hanoi right and just use the again we are doing reader structure out there which is the the salesman logic right thank you very much thanks a lot thank you
Info
Channel: Questpond
Views: 41,829
Rating: undefined out of 5
Keywords: static, c# singleton, singleton class in c#, static class in c#
Id: csQdTkEdhME
Channel Id: undefined
Length: 31min 44sec (1904 seconds)
Published: Sun Jul 05 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.