StaticKeyword.mp4

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
In this video we will talk about what is the use of Static keyword in C#. This question probably looks very basic and if you ask developers Most of them will end up saying that it is use in factory patterns it is used in singleton pattern it is used for sharing data etc I think patterns are just the buy products of static keyword and the existence of the static keyword was for 3 basic purposes In this video we will unleash what those three basics purposes are IN order to understand the use of static keyword lets consider this simple project here called as SomeApplication It has 2 class libraries one is the customers and the other one is the masters The masters library has a simple class called as country master It has three properties CountryCode CountryName and ComputerName The country code is it will have three letter symbol which represents a country and the country name is the full blown textual name of the country The computer name has the current machine name There is also a insert function the insert function inserts the country record into database and while inserting it also uses a computer name property to tell from which computer this record was inserted The second library i.e a customer library has a simple customer class This customer class has three properties there The first property is the customer code the second property is the customer name and the third its not a property but its a simple variable i.e a machine name There is a IsEmpty function which actually checks if the string is empty or not. In other words if you see the IsEmpty function it takes up value and in case there is no value it just returns true saying this is empty or else it returns false There is a function called as public void insert now. This insert function actually inserts this customer class into database Before inserting it checks if this customer code and customer names are empty Then we will not then let insert happen or we will say let the insert happen But the problem with the customer class is the machine name This machine name actually it should have the current computer name while inserting this record into database so we can track from which machine this customer record was inserted If you remember our country class had a the logic by which it actually treas the machine name Rather than writing a duplicate logic over here we would like to use that logic so we don't need to write redundant code or we don't need to write the duplicate code In order to consume the computer name logic go to the country master class The get computer name logic the logic which gets the computer name this property is actually private In order to consume this function or this property in the customer class we need to make it public or else it won't be available The properties of the country master first is country code and the country name check if these two properties are empty or not While we are inserting this function we would like to check if these two properties are empty or not We would like to use or reuse the IsEmpty function of the customer class rather than writing the complete logic again in the country class we would like to reuse this logic here Its a private function I have made it as public In other words the country master class had a very nice logic which actually gets a computer name and that logic we wanted to use it in the customer class We made that property as public and in the same way the country master wanted to consume this IsEmpty logic here IsEmpty check logic so we made this as public While we did this we violated encapsulation In order to understand the violation of encapsulation lets consume both these components or both these classes i.e customer and masters in our project called a SomeApplication. This SomeApplication is a command line application its a simple console application Import both the namespaces i.e customer as well as our masters Now create a simple customer object as well as create a country master object In the same way create a country master object Try to see the properties of oCustomer There are some properties which comes from .NET like Equals, GetHashCode, GetType, ToString we won't talk about that but lets talk about properties and functions which are exposed by us We have exposed customer code customer name insert and IsEmpty There us a clear violation of abstraction. Abstraction means that show only what is necessary External person who is consuming your customer class what should he see He should see customer code he should see customer name he should see a insert function but the IsEmpty function is not understood A customer component or a customer class when somebody using it what is the IsEmpty function doing there what exactly it is meant for Your customer class has the abstraction what is exposing it to the external world is now confusing Thats one big problem here. In other words as we were making the functions public we have violated encapsulation or I'll say rather our abstraction is not so simple as it should be In the same way things are also not good with the country master object now Country class or a country object should have country code it should have country name it should have a insert function but somebody who is using a country class he has no idea why a country class has a computer name or a machine names because this computer name we made it as public violating encapsulation and because we violated encapsulation the abstraction doesn't look so simple In other words we have increased reusability but as we increase reusability we have started violating the basic object oriented principles in other words our country class is now showing a computer name property which can be very confusing at time and in the same way our customer class is now showing out is this empty function which again can be very confusing How do we solve this? The answer is simple just create one more class library or a project library And move those functions in that class library Create a simple class library called as Utility In this class library move both of these functions i.e the computer name the which gets a computer name as well as the Empty check function Here is our utility class give a nice class name to this saying CommonRoutines This CommonRoutines is a class which will have these kind of unrelated functions which we would like to reuse in many of the classes and also we would like to preserve our object oriented principles Take this computer name from here I have already taken the IsEmpty function I have already moved the IsEmpty function here from the customer class And also I have moved the computer name logic Make this as a function here Both the logics the both these functions which were causing the problem of abstraction which were causing the problem of encapsulation we have moved them into a separate class library called as Utility and we have clubed them into a class called as CommonRoutines class Lets reference this utility class in both the customers as well as the master library over here First start with the customer class and import the utility namespace here So we can start using the the utility classes here Now create the object of common routines class If you remember common routines class actually belongs to the utility namespace Lets invoke the IsEmpty function which belongs to the common routines class We are now able to achieve reusability second the insertion should happen only if it is not IsEmpty We need to flourish the machine name variable using the common routines class Use a common routines to get the machine name and flourish the machine name in the customer class This machine name variable will flourish inside a constructor so as soon as the customer class object is created will flourish the machine name Lets define a constructor here called as customer class Inside this create the object of common routines and flourish this machine name with the current machine name In the same way modify also the country master class We have imported the utility namespace I'll keep the same structure i.e I am not going to change the computer name property I'll just create the common routines class and wherever it was Using that return system.environment.machinename I am going to just invoke the common routines class here The complete code is centralized in the utility class and in the same way I can use the IsEmpty function I need to create the object of common routines again here We want to check the country code as well as country name. First check for the country code as well as I am going to check it for the country name Because we have centralized our code inside the common routines class I can reuse this code both in the country class as well as I can reuse this code in my customer class. In that way I have not violated encapsulation My country class as well as my customer class both are maintaining there sanity and also I have made a cleaner solution by introducing the utility class This is a perfect solution This solution doesn't look weird its a decent solution. Many people would agree to it But again there are some concerns here Lets talk about those concerns In order to understand the problem in a better manner Lets first speak about this utility class more. In other words lets try to analyze this utility class in a better manner If you closely watch the utility class is a collection of methods, functions and logic which are unrelated in other words You saw in current scenario the get computer name and the IsEmpty functions are completely unrelated. They don't have any connection with each other as such Its a utility class which can have anything in the world Because it has unrelated methods, function and logic it does not represent any real time objects. In other words when we talk about object oriented programming or when we talk about classes Classes represents some kind of a real world object but here because we are we have made the utility class in order to see that we don't have redundant code and in order to ensure that current customer class and the master class they do not violate encapsulation they are pure that's why we have created it Because of this unrelated functions and unrelated methods this utility class does map you any real world object That is a first point to note here If you say that this utility class is a collection of unrelated methods its a collection of unrelated function its a collection of unrelated logic It does not represent any kind of real world object Any kind of object oriented principles should not be allowed to be applied on this utility class. In other words Nobody should be able to inherit this class Nobody should be able to create interfaces or nobody should be able to apply interfaces over this class The abstract classes should not be allowed on this class Polymorphism should not be allowed on this class because this class does not represents any kind of real world object In simple words this is a fix class. A class which has a fix behavior whose behavior cannot be changed by inheritance. Whose behavior cannot be ploymorphised by using a dynamic polymorphism or a static polymorphism This class is a fixed class or I'll say rather this class is static class How do we avoid inheritance? How do we avoid interfaces? How do we avoid abstract keyword? over this class and that is by using the static keyword In order to make this class as static we need to use the static keyword here If you make a class static all of the functions, the variables everything inside the class should be static We need to make IsEmpty function as well as the get computer name function as static which I have already done here And once you compile you will get lot of error here and the most significant error is you can't use anymore the new keyword on the common routines class so you have to invoke it by the class name and then the function name or the method name which we want to invoke Because this is not real world object it doesn't make sense to use the new keyword on it By default internally only one instance of the static classes created which will will serve any clients who connect to him Delete this new keyword and directly use the class name of the static class the class name of the of the static class and straight forward we will invoke the functions here I am replacing each method here Compile this We have went ahead and we have made the classes static and because the class is static we also need to make the functions and the methods as static we did that And once you compile it you got error stating that you can't use the new keyword and i.e right because its not a real world object To invoke the functions we have to say ClassName. directly the function name which we did and now we have compiled the complete project and looks okay Just out of curiosity we would like to see that if any object oriented principles actually works on this CommonRoutines class Let me try with inheritance create a class here called as my own CommonRoutines and let me try to inherit the CommonRoutines class In other words all those principles of object oriented Programming should not be any more applicable to this class Its clearly showing me error there saying you cannot inherit the common routines class while its a static class If you try to build this you can see error saying that it cannot derive from a static class which is your Utility.CommonRoutines Inheritance doesn't work on this Lets try some other things like interfaces and abstract classes Inheritance doesn't work. Let me try to create a interface If interfaces are working on the class then again polymorphism will work dynamic invocation will work etc Here I have created a interface I1 and it straight forward saying me that static class cannot implement interfaces Its stopping all those object oriented programming concepts to be applied to this static class Inheritance doesn't work Let me try the abstract keyword If you are able to make this as abstract class which we cannot write because as I have already said You can see that static classes cannot be abstract class Most of the object oriented programming concepts are not applicable anymore to this static class and which is what we want This CommonRoutines class does not map actually to any kind of real world object It is just a collection of unrelated functions and methods or logic So that we can increase reusability in our project or we can increase technical reusability Its a technical object but its not a real world object and it make sense that any of those object oriented principles are not applicable to this CommonRoutines class Our utility class is now in a nice shape Probably tomorrow nobody can do inheritance on this nobody can apply polymorphism and with this any kind of bad design will be avoided There is one big problem here At the end of the day its a class you say that we cannot apply inheritance we cannot apply polymorphism We cannot apply interfaces To use that class it has to be instantiated If it is not instantiated you will never invoke those functions and those routines How do we go about instantiating this object or how does the instancing or how does the instantiation of this utility class actually takes place internally In order to overcome this problem regarding instantiation What the CLR runtime does is it creates one instance of the static class In our current scenario The utility class which is been used by both the customer class as well as the customer master class Country master class. Irrespective how many times this utility class is called? There is only one instance of the object who is going to serve each of those clients. In other words new instance will not be created Because of this single instance behavior of static classes The static classes also are used in scenario when we want to share common data For example you want to share configuration data in your in your windows application. For example let say you have 50 60 forms and every time those forms run you would like to share some common data You can make a class as a static you make the variable as static Only one instance of the object will be created in the memory and thus all the forms can share the common data The instantiation problem is solved by creating only one instance of the objects Static classes has only one instance of the object created ion memory Lets try to see if only one instance of the object is created or not Go to a CommonRoutines class here and crate a simple variable called as some kind of a counter variable This counter variable will be incremented every time either the customer class or the master class actually invokes this invokes the common routine methods I have created integer variable here As I said that you cannot have simple instance members inside static classes. You have to have those members as static We need to say this cannot be simple public int You have to say it has public static int This how many times variables will increment every time whenever we call this IsEmpty function or we call the GetComputerName function Every time you invoke a function over this common routine. I am going to increment this variable Go to our SomeApplication which we have created and invoke these functions i.e the customer methods as well as the master class methods First reference both these classes here and import the namespaces Every time the insert us called for both customer as well as a master classes It will increment the how many times counter Take the utility class here because I'll need the utility class to display what is a value current counter value. How many times values First create the customer class and invoke the insert function in the same way create the master class and invoke the insert function Irrespective the customer object is new. There us new keyword over there the country master object is new but inside the utility class the commonRoutines class will have only one inserts running Every time that how many times +is added it will actually accumulate on the same. It will not replace refresh the values In order to ensure that what we will do is lets display the how many times value here I have called the inserts three times one for the customer class and once I have called for the master site The how many times should show me the number as 3 In other words if it is using the same class If it is using the same instance then it actually just increment the value over it rather than refreshing it I am going to say here display me how how many times value I should see now the value as 3 3 means the CommonRoutines has only one instance of the object running in memory Build this Also do a ReadLine here so you can see what the value is or else it will just go off I am seeing value.length == 0 I have not handled null On nulls you can't invoke the properties like this Fix this up here Before I check even the length = 0 or rather I'll use a string function here I'll say string.check it is null or empty either it is null or either it is empty this will throw up exception Nulls are different empties are different. They are not same thing. Now build this I should see the value as 3 Because 3 times inserts are called Even if they are called different classes or different instances Only one instance of your CommonRoutines class exist and that instance how many times variables is updated rather than refreshing the values. Dispose that only one instance of the object is created for the CommonRoutines class Because only one instance of the object is created it also signifies is that the constructor will run only once which is again very important point to note The time you call the first method the first time any client calls the first method on this CommonRoutine It will create a instance and after that the constructor will never run The constructor will also run only once I have created a constructor here on the CommonRoutines class and I put a debug point If I run this This is a first invocation happening on the CommonRoutines class i.e GetComputerName The constructor is running there After this the constructor will never run because only one instance is created When I am calling the insert again I am calling the IsEmpty function and again I am calling IsEmpty function for customer name and customer code but its not invoking the constructor now anymore The constructor also runs only once because only one instance of the object is created in memory This is again one of the very important point to remember about static class. The constructor runs only once in a static class now because of the single instance behavior static classes are also good candidates for crashing data In order to understand how we can implement crashing using static classes Create a simple collection here of string and this collection will have weeks like sunday, monday, tuesday etc Collection will store the week days Collection objects are not good candidates for storing week days ENUM should be a good candidate or a good choice. For now for the cash demonstration purpose we will use this collection This collection will be flourish in the constructor. I have created a simple constructor of CommonRoutines and in that that constructor we will flourish the week days i.e sunday, monday etc Now add the weeks into the OWeeks string collection I have flourished the collection in the constructor of CommonRoutines As we know we have only one instance we created This constructor will run only once it will not run again and again Write a simple for each loop which will browse through the string collection and display the weeks on to the console application I have started the debugging You can see the constructor runs only once After that OWeeks is catched into a in memory After that anytime you browse the OWeeks using the OWeeks collection using the CommonRoutines class it will always comes from the in memory cash it will not come again and again Because of the single instance nature of static classes its also a good candidate for cashing purpose Lets summarize what exactly we have learned in this 30 minutes video There are three important use of static keyword. First one is it helps you to group unrelated functions and methods together. For example like a Utility class Second because one instance of the static variable is created in memory If you want to share common data across class libraries or if you want to share common data across forms Static objects are very useful And third one is if you want to catch data. For example if you have a country master rather than hitting the database again you can load the country master into a static variable or a static list or collection Then you can look up the list again and again rather than making round trip to SQL Server or to your RDBMS These are the three important use of Static Keyword I hope you enjoyed this video. Next time when you see a static class or a static method or static variable you understand in what kind of scenario they are useful and what scenario is fit in Keep visiting questpond.com for such kind of videos Thanks you very much
Info
Channel: .NET Interview Preparation videos
Views: 49,128
Rating: 4.7731342 out of 5
Keywords: what is static keyword, c# static keyword, explain static keyword with example, c# tutorial youtube, c# keyword, c# interview questions and answers, c# interview questions, learn c# step by step, c# step by step tutorial for beginners, static c# keyword, static keyword step by step tutorial, tutorial on static keyword, explain c# static keyword, c# programming for beginners, c# programming language, learn csharp, use static keyword in c#
Id: xByUSk-5sRs
Channel Id: undefined
Length: 31min 22sec (1882 seconds)
Published: Thu Sep 08 2011
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.