Introduction to Delegates in C#
Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at detailed Introduction to Delegates in C#. It's our 21st tutorial in C# series and now we are entering in the complex field. C# concepts, we have studied so far, were quite simple, but now we are slowly moving towards complex topics.
Delegates are not that difficult as normally considered, you just need to understand its basic idea and rest is quite simple. So, let's get started with Introduction to Delegates in C#:
Introduction to Delegates in C#
- Delegates in C#, created by using delegate keyword, are used as a type safe pointer, normally pointing towards C# Methods & Events.
- The signature of the Delegate & the function ( its pointing to ) must be same.
- As Delegate is a reference type Data type, so we can create its new instance.
- If you want to use any Method as a variable, then Delegates are literally the answer. ( We will have a look at it shortly )
- Delegates belong to builtin C# class named System.Delegate.
- Let's have a look at it's syntax:
- You can see in above figure that I have first declared the delegate, outside the class and I have used delegate keyword in its definition.
- Now in the Main function, I have created a new instance of this Delegate and in its constructor, I have pointed out the Method Name, to which I want to assign this delegate.
- After that I have invoked the Method using Delegate, instead of the Method's name itself.
- You need to make sure that signature of this delegate & the function must be same, when I use the word signature then that means return type and parameters.
- My Function & delegate, both have void return type, so if I change return type of any one of them, then compiler will generate an error and that's why we call it type safe.
- Similarly, the number & type of Function Parameters must have to be same for both Delegate & its pointed Method.
- Let's have a look at MultiCast Delegate in C#:
MultiCast Delegate in C#
- We can assign / point a single delegate to multiple Methods / Functions, such delegates are called MultiCast Delegates in C#.
- In the below figure, I have assigned a single delegate to 3 methods and when I invoked the delegate then it has executed all these 3 methods.
- In the above figure, I have used two ways to chain delegates together, in the first way I have used plus sign ( + ), while in second one I have used append sign ( += ).
- You must be wondering why to use these function pointers when we can directly invoke the Method using its own name.
- So, in order to understand the importance of delegates, let's design a simple example:
Example of Delegate in C#
- Let's create simple code, where we create a new class named StudentsData and it will have 3 C# Properties and 1 C# Method.
- You can see this code in below figure and I have placed an if loop in my method which has a Boolean expression in it i.e. score < 40.
- This condition Score < 40 is hard coded in my method, which makes my code quite rigid, whereas its always good practice to add flexibility in your code so that you could reuse it.
- So, now let's create a new method and add a delegate instead of this Boolean expression and as its a Boolean expression, so my delegate also has to be of Boolean return type.
- You can see in above figure that I have created a delegate named StudentsDelegate, which is of Boolean return type.
- After that, I have created a method in Main Function named CheckStatus, which is also of Boolean Type and taking Score as a parameter.
- If you look closely, the signature of this delegate & method CheckStatus are same.
- I have used the delegate to point to this method CheckStatus and have placed our failed condition in it.
- Now this function will return either TRUE or FALSE i.e. it's kind of a Boolean expression.
- Finally, I have added a delegate as a second parameter in FailedStudents Function, and then used this parameter as a condition in IF Loop.
- So, now my class is completely flexible, if I wanna change the condition, then I don't need to change the class, I can change score condition in my Main class.
- Now, you must be thinking, we have done so much coding just to shift a condition from one class to another, we have done it for a purpose.
- So, let's have a look at the below image, where I have used Lambda Expression in C#:
- In C#, we can use lambda expressions, which we will study in coming lectures, but for now you can see in above figure that I have removed the delegate instantiation and have also removed the pointed method.
- Instead I have just placed a Lambda expression and visual studio has created the delegate & method in the background, which we don't need to worry about.
- We just need to understand this lambda expression where we have placed our condition i.e. Score < 40.
- Delegates are the basis of this lambda expression, which is quite handy, it has not only made the class flexible but have also reduced the code to just single line.
So, that was all about Delegates in C# and I hope you have understood their importance. In the coming lecture, we will have a look at Exception Handling in C#. Till then take care & have fun !!! :)
Introduction to Properties in C#
Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at Properties in C#. It's our 20th tutorial in C# Series and a quite important one as we are gonna use properties a lot in our coming lectures.
If you haven't studied
C# Methods &
C# Classes then I would suggest you to read them first before starting today's tutorial, as we are gonna use methods today. So, let's get started with Properties in C#:
Introduction to Properties in C#
- Today I am not gonna start with the definition as I did in previous tutorial, instead we will first understand the concept and then will define it.
- So, let's create a new C# Class named StudentsClass shown in figure on right side.
- this class has 3 fields in it, first one is int and other two are string and all these three fields are public.
- Moreover, it has a C# Method in it, which is also public and printing the Full Name.
- In our Main Function, I have created new instance of this Class and then invoked the Method.
- So what if, we want to add some restrictions on these fields i.e. we can't have a negative roll number & the name fields can't be null.
- We don't want garbage values as well, to pass on to our project so its always wise to use private fields instead of public and place some controls on the coming values.
- We can do this by using C# Methods, as I did in this right image. ( you may need to click the image to look at the zoomed version)
- So, here I have created two C# Methods, which are receiving values from external classes and then I have placed the check on the coming value and if it satisfies the condition then I have passed it on to my field or variable.
- Now the field is also private, instead of public.
- But you must be wondering that its a lot of work to add two functions for every field, so here comes the properties in C#.
- In the below figure, I have created a C# Property named RollNo for the private field _RollNo and then I have used accessor in C#, which are:
- set: To save the value of Property.
- get: To read the value of Property.
- In the above figure, you can see that I have created a property named RollNo and in that property, I have used set accessor & get accessor.
- Moreover, in the Main function, now we are treating RollNo as a Property and using dot operator to set or get the value.
- Instead of using the setRollNo function, we are simply using SC.Roll = 20; to set the Roll no. and compiler will automatically move to set accessor of this property and the value we will assign it i.e. 21 it will be used by the value keyword.
- You can see in set accessor that, I have used value keyword and this keyword will have the value coming from invoking request i.e. 21 in our case.
- Similarly, when we want to read the Roll No, we are using SC.RollNo and the compiler will automatically know that it need to move into RollNo Property and then check the get accessor.
- So, we can say that our property RollNo is a read / write property, if it just has the get accessor then it will be read only property.
Auto Implemented Properties in C#
- In the above case, we have seen tha we have to place some logic in our set & get accessor, but in most of the cases, we don't need to add any additional logic in our accessors.
- For example, I am creating fields for City, Phone Number, Email Address etc. then in such cases, we can make use of C# Auto-Implemented Properties which were introduced in C# 3.0.
- In the below figure, I have created Properties with get & set accessors:
- You can see that now I have created 3 new C# Properties and haven't even created any field for them, that's created & implemented automatically by C#.
- So, when I create a C# Property then its auto-Implemented its private field, which we can control by using set & get accessors, if we want to.
- So, our whole field vanished & protected and our new Property code is also lies in just one line, so kind of brilliant idea, introduced in C# 3.0.
Object Initializer Syntax
- Now let's have a look at a new Object Initializer Syntax, which was also introduced in C# 3.0 and I think it's best among all.
- Let's instantiate our StudentsClass using this new Object Initializer Syntax, as shown in below figure:
- You can see in above figure that it's now quite simple to assign & get data to & from Class Properties.
- I am updating all Members of C# Class in just single line, although you can add single property per line as well, but I like it that way, simple and clear.
So, that was all about Properties in C# and I hope now you can set & get them quite easily. In our coming tutorial, we will have a look at Delegates in C#. Till then take care & have fun !!! :)
Introduction to Abstract Classes in C#
Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at detailed Introduction to Abstract Classes in C#. It's our 19th tutorial in C# series. Today, we are gonna discuss another new concept in C# and I would recommend you to follow these tutorials at least 3 to 4 times, so that these concepts find the right place in your brain and stick there.
C# Abstract Classes are quite similar to C# Interface in many respects, so if you have studied previous tutorial in C# Series, then do read it first. So, let's get started with Introduction to Abstract Classes in C#:
Introduction to Abstract Classes in C#
- Abstract Classes in C# are created by using Abstract Keyword, and are used to create abstract members, which have their declaration but no implementation (as in C# Interfaces) but unlike Interfaces, Abstract Classes can also have complete methods, properties etc.
- Abstract Methods in C# are also created by using Abstract Keyword, these methods are only declared in Abstract classes and are then implemented in one of its derived classes & the implementation of the Method must have override Keyword in it.
- You must be finding these definitions a bit difficult but no need to worry as we will discuss them one by one in detail.
- The Abstract Modifier / Keyword is used to indicate an incomplete implementation that's why we can't instantiate such objects. We can use it with classes, methods, properties, events and Indexers.
- Moreover, the class inherited from Abstract Class must have the complete implementation of all the members of Abstract Class, along with override keyword in their declaration. (We will discuss it shortly)
- It's not compulsory for the Abstract Class to must have some Abstract members, instead we can add only normal members as well.
- Let's have a look at the syntax of Abstract Class having 1 Abstract Method & 1 normal Method, shown in below figure:
- In the above figure, we have created a public class with abstract keyword/modifier in it named StudentsAbstract, so it's an abstract class.
- As StudentsAbstract is an Abstract Class, so we can create both Abstract (Incomplete) members and normal (complete) members in it.
- So, I have created two methods, printMsg() is an abstract Method as it has Abstract Keyword in its declaration, that's why we haven't placed the implementation of this method.
- While printMsg2() is a normal method so it's fully implemented in Abstract Class.
- These Abstract Classes are normally used as a Parent Class in Inheritance and it's kind of their main role. So, let's have a look at Inheritance in Abstract Classes:
Inheritance in C# Abstract Classes
- As I mentioned earlier, Inheritance is the main role of C# Abstract Classes and they normally play the role of Parent Class and we inherit different classes & structs from them.
- We can't use the sealed keyword with abstract class, as then we can't inherit any other class. ( We have studied sealed keyword in C# Classes Lecture )
- Abstract Class can inherit from other Abstract Classes & C# Interfaces. ( Interfaces can't inherit from Abstract Classes )
- The class inherited from Abstract Class, must have the implementation of all abstract members of its Parent Class, otherwise, we will get a compiler error.
- In the above figure, we can see that I have added a new class StudentsClass derived from our Abstract Class StudentsAbstract.
- Now, this new derived class must have the implementation of its Parent's Abstract Members, as I did for printMsg() Method in above figure.
- Moreover, we need to use override keyword in our derived class method's declaration.
- So, now we have created an Abstract Class and have also added an Abstract Method in it, after that we have derived a new class and provided implementation of our Abstract Method.
- Let's now invoke this Abstract Method, declared in Abstract Class & Implemented in Derived Class, shown in below figure:
- In the Main function, I have simply created a reference variable of Child Class and then invoked both of these methods.
- You must have noticed that Abstract Classes are quite similar to Interfaces but they have few differences as well, let's have a quick look at them:
Abstract Classes Vs. Interfaces
- Abstract Classes & Interfaces have a lot in common as both are used for creating incomplete members i.e. declaration only, yet they have some differences as well.
- We can't create implementation of any member in Interfaces but that's not the case in Abstract Classes, we have the option to create Full members in Abstract Classes.
- Members in Interfaces can't use access modifier and they are all public by default, but in Abstract Classes we can provide access modifier and can make them private etc.
- We can't declare C# Fields in Interfaces but that's possible in Abstract Classes.
So, that was all about C# Abstract Classes and I hope you can now differentiate them from Interfaces. In the next lecture, we will have a look at Introduction to Delegates in C#. Till then take care & have fun !!! :)
Introduction to Interface in C#
Hello friends, I hope you all are doing great. In today's tutorial, we will discuss another important concept named Interface in C#. It's our 18th tutorial in C# series. It's one of my favorite concepts in C# as its come quite handy in complex projects.
Interfaces are quite similar to
C# Classes &
C# Structs in design so if you haven't studied those lectures then do read them first. So, let's get started with the Introduction to Interface in C#:
Introduction to Interface in C#
- Interface in C# is created using Interface Keyword and is used for the declaration of Methods, Properties, Events etc. but we can't add any implementation in it. ( we can't declare Fields in Interface )
- You can think of Interface as a signature, you look at the interface and you will know all Methods, Properties etc. used in your project.
- Interface members don't use access modifier in their definitions, by default they all are public.
- It's a naming convention to use capital ( I ) as the first character of interface name, so that you know, just by looking at the name, that it's an Interface.
- Let's have a look at the syntax of Interface , before exploring it any further:
- In the above figure, I have created an interface named IStudentsInterface and it contains declaration of two C# Methods.
- We can't implement these methods in Interface, as it will generate a compiler error.
- Now you must be wondering, what's the benefit of using Interfaces, when we can't add the Implementation, and here comes Inheritance:
Interface Inheritance in C#
- Interfaces are normally used as Parent Node in Inheritance, while C# Classes and C# Structs are inherited from Interfaces.
- We can inherit a class or struct from multiple Inheritances, separated by commas. (We can't inherit a class from multiple classes)
- When we inherit a C# Class or Struct from an Interface, then it must provide the implementation for all the Members of that Interface.
- If we miss implementation of any single member, then compiler will generate an error.
- We can't create a new instance of Interface as we can do for Classes & Structs, although we can create an Interface Reference variable that will point to its derived class object.
- So, let's inherit a C# Class from our interface IStudentsInterface and see How it works:
- In the above figure, I have created an Interface named IStudentsInterface and it has declaration of two Methods i.e. PrintMsg() & StudentsNames().
- After that, I have inherited a class named StudentsClass from this interface IStudentsInterface .
- This class must have the implementation of those two methods we declared in our Interface IStudentsInterface.
- So, I have just created two simple methods with Console ouput, so we remove any one of them, the compiler will generate an error.
- Let's inherit our class from multiple interfaces, shown in below figure:
- In the above figure, I have created two C# Interfaces having 1 Method each.
- Moreover, the class is inherited from both of these interfaces, separated by commas, so it must have the implementation of both of these methods.
- Similarly, if an interface is inherited from another interface and you are inheriting your class from Child Interface, then still you must have the implementation of all Members of these two Interfaces in your class.
- Let's have a look at this multiple level inheritance of Interfaces:
- You can see in above figure, that IStudentInterface2 is inherited from IStudentInterface and our class is inherited from IStudentInterface2. (Like a chain)
- So, in this case as well, our class must have the implementation of both these methods, otherwise we will get compiler error.
- This type of Interface Members' Implementation in C# Classes or Structs is called Implicit Interfaces Implementation.
- So, now let's have a look at Explicit Interfaces Implementation:
Explicit Interfaces Implementation
- In Explicit Interfaces Implementation, we have to use the Interface Name along with dot operator and then name of the Method in its implementation.
- An example of Explicit Interfaces Implementation is shown in below figure:
- As you can see in above figure that our class is inherited from two interfaces.
- Moreover, in this class I have implemented C# Methods explicitly i.e. now compiler won't need to find which method belongs to which interface.
- Instead the interface name is present in Methods' definition along with dot operator ( . ).
- You must have noticed that now we have removed the access modifier and its public by default as of Interface members.
- When Interface members are implemented explicitly, then we can't access them using reference variable, instead we need to use cast operator:
( ( IStudentsInterface) SC ) . PrintMsg();
- So, we need to use above method in order to invoke the Explicitly Implemented Interface Method.
- There's another way as well, which I have told you at the very top of today's tutorial i.e. we can't create a new instance of Interface yet we can create its reference variable, as shown in below figure:
- You can see in above figure that in Main function, I have created Interface variables both pointing to its derived class object.
- Now, as they are interface variables so we can use them to invoke respective explicitly implemented method.
So, that was all about Interfaces in C#. I hope you have completely understood its operation and working. In next tutorial, we will have a look at Abstract Classes in C#. Till then take care & have fun !!! :)
Introduction to Structures in C#
Hello friends, I hope you all are doing great. In today's tutorial, we will have a detailed
Introduction to Structures in C#. It's our 17th tutorial in C# series. Structures are quite similar to classes but have few differences as well, which we will discuss today.
We have discussed
C# Classes in 13th lecture, so you must read it once as we will use that knowledge in today's lecture as well. So, let's get started with Introduction to Structures in C#:
Introduction to Structures in C#
- Structure in C# is a value type data type, created by using keyword struct, and can have fields, methods, properties, operators etc. just as in C# Classes.
- Main difference between C# Class & Structure is that C# Class is a Reference Type Date type while C# Struct is a Value Type Data type.
- Let's have a look at the syntax of C# Structure:
- You can see in above figure, that we have created a struct in C# named StudentsData and it has two private fields in it i.e. ID and Name.
- This structure declaration is quite similar to that of C# class and the only difference is that we have used struct keyword here, instead of class keyword.
- So, now let's add a C# Method in this structure and then invoke it from Main Function, shown in below figure:
- So, you can see in above figure that we have invoked structure in the same way as we invoked C# Class.
- We have first created a reference variable for C# structure and then invoked the Structure Method. ( as we did for C# Class )
- We can't inherit a structure from a Parent Class or any other struct but we can inherit a class from a structure.
- Both Structs & Classes can inherit from an Interface. ( which we will study in next lecture)
- C# Data Types i.e. int, float, double are examples of Struct in C#.
- Structs are stored on Stack while we use Heap for storing C# Classes.
- Let's have a look at Struct Constructor, which is slightly different than Class Constructor:
Struct Constructor in C#
- Structures in C# can't have destructors, if you add a destructor in struct, then compiler will generate an error.
- Although you can create a Constructor in C# Struct but make sure it has some parameters in its definition.
- A parameter-less constructor is not allowed in Structures but you can overload Struct Constructors.
So, that was all about Structures in C# and you must have noticed that they are just Value Type version of C# Classes, which are actually Reference Type. In the next lecture, we will have a look at Interface in C#. Till then take care & have fun !!! :)
Introduction to Polymorphism in C#
Hello friends, I hope you all are having fun. In today's tutorial, we will have a look at
Introduction to Polymorphism in C#. It's our 16th tutorial in C# series and polymorphism is considered as a main pillar of object oriented programming.
In our previous tutorial, we have seen a detailed
Introduction to Inheritance in C# and along with it, we have also discussed How to hide a Method in Parent Class, if the same method exists in Child class. This Method Hiding is actually the basis of Polymorphism, so let's discuss it out in detail:
Introduction to Polymorphism in C#
- Polymorphism in C# enables the user to invoke a Child Class Method & override the Parent Class Method, using a Parent Class Reference variable.
- In our previous lecture on Inheritance, we have also discussed method hiding and our last code is shown in below figure:
- In the above code, you can see that we have used method hiding by using new keyword with ChildClass Method.
- So, now instead of hiding the method let's override it and have a look at the results:
- In the above figure, you can see that I have used virtual keyword with Parent Class Method.
- Moreover, instead of new keyword, I have used override keyword with Child Class Method.
- I have used the same reference variables as I did for Method Hiding code, but here in the third case, the child class method is called.
- So, in Polymorphism, if the Child Class is involved in reference variable, then it will always override the Parent Class Method and will use the Child Class Method.
- So, we can say that if we want to completely override any function in Parent Class, then we need to add virtual keyword in its definition.
- This virtual Parent Class Method will always get override by any Base Class Method, which has the same name and has override keyword in its definition.
- But if we want to invoke the virtual Parent Class Method, then we have to use Parent Class reference variable.
- So, this third variable PC2 is the main difference between Method Hiding & Method Overriding (Polymorphism).
So, that was all about Polymorphism in C# and if you have got the Method Hiding then it won't be much of an issue for you. In the next lecture, we will have a look at Introduction to Structures in C#. Till then take care & have fun !!! :)
Introduction to Inheritance in C#
Hello friends, I hope you all are having fun. In today's tutorial, we will have a detailed Introduction to Inheritance in C#. It's our
15th tutorial in C# series and again an important concept in Object Oriented Programming, as it helps in code optimization.
In our previous tutorial, we have discuss
namespaces in C# and that was the last storage item in C#. Today, we are dealing with entirely different entity, which is inheritance. So, let's discuss it in detail:
Introduction to Inheritance in C#
- Inheritance in C# is used to create a relation between two classes. In simple words, derived / child class is inherited from base / parent class and will automatically have all its members as its own. Inheritance is denoted by ( : ).
- Mostly in projects, there are few functions which we have to use a lot throughout the project, so we can place such functions in any parent class and then which class needs those functions, we can simply inherit it from that parent class.
- Here's the syntax for inheritance, where ChildClass is Inherited from ParentClass, so ChildClass can use all functions and fields of ParentClass:
- When we create a new instance of any child class, then parent class constructor executes first and then child class constructor executes.
- So, in below figure, I have created two classes, ChildClass is inherited from ParentClass and I have also created their Constructors.
- Mow in the Main function, I have created a new instance of ChildClass and you can see in the Console that first Parent Constructor Called & then Child Constructor Called.
- Suppose, you are designing a software for college class, where students have few same subjects but some different subjects.
- Let's say, Engineering students study Physics & Chemistry while Medical students study Biology but they all have to study Mathematics & English.
- So, I have created one Parent Class with name MainSubjects, which has the compulsory subjects in it.
- Then I have created two Derived Class named MedicalSubjects & EnggSubjects and I have derived both of them from Main Subjects, so they can use both Maths & English fields.
- You can see inheritance in above figure, in the definition of class we have MedicalSubjects : MainSubjects, so MedicalSubjects is inherited from MainSubjects.
- In the Main code, I have created new instance of MedicalSubjects & then updated score for English, which is actually in MainSubjects, and it updated correctly.
- So, I can use all members of parent class in derived class.
- The benefit of Inheritance is that, it allows user to reuse old code without writing it again, so it saves time and reduce errors.
- C# allows single class inheritance i.e. we can't derive class A from two different classes at the same time.
- C# allows multiple Interface inheritance, which we will study later in detail.
Now I hope you have understood How to use Inheritance in C#, so now we are ready to discuss a similar concept called Method Hiding, it's related to Inheritance so let's have a look at it.
Method Hiding in C#
- Method Hiding in C# is a simple technique, where we declare two methods with the same name, one in Child Class & other one in Parent Class and the Child method will hide the parent Method, if called from Child Class Reference Variable.
- We need to use new Keyword with the child class Method, which will hide the old Parent class method.
- In our previous part, we have seen How to use Inheritance and have created Parent & Child class.
- Now, let's create two Methods with the same name, one in ParentClass & one in ChildClass, as shown in below figure:
- You can see in above figure, that I have created a Method PrintMsg() in both ParentClass & ChildClass.
- In the Main Function, I have created 3 reference variables, which are:
- PC is a ParentClass variable, pointing to ParentClass Object.
- CC is a ChildClass variable, pointing to ChildClass Object.
- PC2 is a ParentClass variable, pointing to ChildClass Object.
- You must be wondering about the third variable, yeah we can do that as we can use all members of ParentClass in ChildClass but we can't do the opposite.
- Moreover, when we called the PrintMsg() Function from 2nd variable, which is a ChildClass variable, then it has executed the Function in ChildClass, which has new Keyword in its definition.
- So, the second variable has completely ignored (hide) the method in ParentClass and simply used the new method in ChildClass and it's called Method Hiding.
So, that was all about Inheritance in C#, which is quite simple concept but really effective in complex projects. It is considered as a pillar of Object Oriented Programming. In the next lecture, we will have a look at Polymorphism in C#. Till then, take care & have fun !!! :)
Introduction to Namespaces in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at detailed Introduction to Namespaces in C#. Namespaces are considered as libraries in C#. If you have worked on any other programming language then you must be aware of the term library which contains all classes & methods etc. In C#, this functionality is performed by namespaces.
In 12th tutorial, we have seen
Introduction to Methods and in 13th part, we have seen
Classes in C#. Methods are simple storage units and stores code only, Classes are slightly bigger storage units and can store methods. Now Namespaces are giant storage units, which can save anything in them i.e. classes, methods, namespaces etc. So, let's have a look at them in detail:
Introduction to Namespaces in C#
- Namespaces are giant code storage units, can be referred as libraries in C#, and are used for optimization & orientation of the code.
- Namespaces are included in the project with the help of using directive at the top.
- If you look at our previous codes, then you will find using Systems; at the top of your code, basically this Systems is a namespace and with the help of using directive, we have included it in our project.
- Console, which we use for printing our data, is a member of this System Namespace.
- Our whole project is also placed between { } brackets of namespace TEPProject.
Why we need namespaces ?
- Using Namespace, we can organize the code pretty well, it doesn't have much impact in simple projects but in complex projects, you can't ignore namespaces.
- Throughout our course, we have discussed classroom data and in C# Classes lecture, I have asked you to get data of all classes of a school and now in namespace case, think of data coming from all schools of British School System.
- So, in bigger projects, there's always a need to make different teams, which will be working on separate code departments.
- In such cases, each team can create project with its own namespace and at the end you can use all those namespaces in your Main code and can get access to its functions etc. without disturbing each other's code.
Creating Namespaces in C#
- So, now let's create two namespaces in our project for two different schools, named as SchoolA & SchoolB, as shown in below figure:
- In above figure, you can see our first namespace structure is: Namespace SchoolA > Class TeamA > Method printSchoolName.
- Our second namespace structure is: Namespace SchoolB > Class TeamB > Method printSchoolName.
- Now in my Main function, which is in TEPProject Namespace, I am calling both of these printSchoolName Method.
- In order to invoke the method in first namespace, I have used dot operator and the sequence is SchoolA.TeamA.printSchoolName();
- For the second namespace, I have placed using SchoolB; at the top of the code and now we can call TeamB class directly and that's why I have used TeamB.printSchoolName(); to invoke method in second namespace.
- So, we can use namespaces using these two ways and I prefer the second one as it makes the code smooth, we don't need to write SchoolB every time.
Create Project for Namespaces in C#
- Now you got the idea of what are namespaces and how to use them in C#.
- So now it's time to create separate projects for these two namespaces and you will see our code will become clear & simple.
- Right click on your Project's Name in Solution Explorer and then click on Add and then click on New Item, as shown in below figure:
- When you click on New Item, a new window will open and here you need to select C# class, as shown in below figure:
- I have given it a name SchoolA.cs and then click Add Button.
- Similarly, I have created a new project for second namespace SchoolB.cs and now my Solution Explorer is shown in below figure:
- Both of my projects' codes and Main file code are shown in below figure:
- Now you can see in the above figure that our codes are now quite simple & clear and we have created separate files for our new namespaces.
- C# Classes created in separated files and namespaces are now accessible in our Main Function.
So, that was all about Namespaces in C#, I hope you have understood the main idea. In our next tutorial, we will have a look at Inheritance in C#. Till then take care and have fun !!! :)
Introduction to Classes in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at detailed Introduction to Classes in C#. It's my 13th tutorial in C# series and now we are ready to understand this slightly complex subject in C#.
In our previous tutorial, we have seen
Introduction to Methods in C# which are used for organizing the code and we can add some code in separate methods to make the Main method simple. Classes are slightly bigger storage capacities than methods. Methods can store code, classes can store methods. So, let's discuss classes in detail:
Introduction to Classes in C#
- Classes in C# are referred as storage units for different methods, fields, objects etc. and are used for organizing the code.
- In our previous lessons in C#, we have always taken an example of a classroom but what if we have to create a software for an entire school system.
- In that case, we can create separate teams, dealing with each classroom, so you can think of that classroom as a class in C#.
- Our Main method is in class Program, Let's create a new class for OLevel classroom students:
- so, in the above figure, you can see that I have created a new class named OLevel and this class has 3 members, named as:
- First one is field/variable named: FirstName.
- Second one is field/variable named: SecondName.
- Third one is method named: printStudentName.
- So, we have 3 members in our newly created class and all these members are instance members as they don't have static keyword in their statement.
- So, in order to call this OLevel method in Main method, we have created a new instance of OLevel class, as we did in our previous lecture on methods in C#.
- After that using this new instance of OLevel class, we have invoked the printStudentName method using dot operator.
- When we run our code, we have the Full Name : TEP C#, as given in the code.
- You can also use Constructors & Destructors in C#, but they are not necessary to use, as we haven't used the constructor but our code worked fine.
- So, let's have a look at what are these terms one by one:
C# Class Constructors
- C# Class Constructor is a simple method / function, which gets executed automatically whenever the new instance of class is created.
- It must have the same name as the class itself and it won't have a return type and the access modifier is public.
- Constructors are normally used for initializing data fields or for initial settings of your class methods.
- Let's create a Constructor for our OLevel class:
- In above figure, you can see I have created a new method in our OLevel class and it has the same name OLevel.
- Constructors can also have parameters, so if we want to send some data from one class to another class, we can use these constructor parameters.
- So, now instead of hard coding the data in my new class, I am sending the data, when I am create new instance of class. i.e.
OLevel O1 = new OLevel ( " TEP " , " C# " );
- So, that way I can send multiple data just by creating new instance of class.
- You must have noticed that this C# Class Constructor doesn't have a static keyword in it so its an Instance Constructor.
- So, we can also add a static Constructor in C# class, which don't have any access modifier or return type and just have static keyword in its definition and is executed before instance Constructor.
- Moreover, Destructor in C# is used to clean up any resources used by the class and these destructors are called automatically by the garbage collector so we don't need to worry about them.
- Destructors can't take any parameters and they doesn't have access modifier or return type, they just have a tilled sign ( ~ ) in front of them.
- I have created static Constructor, Instance Constructor & Destructor in below code:
- You can see in above figure, that static Constructor is called first and then instance Constructor is called and finally we printed the Full Name.
- Here's the complete code used in this lecture:
using System;
namespace TEPProject
{
class OLevel
{
string FirstName;
string LastName;
static OLevel()
{
// Static Constructor
Console.WriteLine("\nStatic Constructor Called\n");
}
public OLevel(string Name1, string Name2)
{
Console.WriteLine("Instance Constructor Called\n");
this.FirstName = Name1;
this.LastName = Name2;
}
public void printStudentName()
{
Console.WriteLine("Full Name : {0} {1}\n\n", FirstName, LastName);
}
~ OLevel()
{
// Destructor
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\n\nwww.TheEngineeringProjects.com");
OLevel O1 = new OLevel("TEP","C#");
O1.printStudentName();
}
}
}
So, that was all about Classes in C#, I hope you have understand their basic concept, we will gradually move towards complex codes. In the next session, we will have a look at Introduction to Namespaces in C#. Till then take care & have fun !!! :)
Introduction to Methods in C#
Hello friends, I hope you all are doing great. In today tutorial, I am going to give you a detailed Introduction to Methods in C#. It's our 12th tutorial in C# series. So far, we have covered all the basic concepts in C# and now it's time to move forward and have a look at some complex concepts.
Methods have an important role in C# programming and if you want to be an efficient programmer then you must set your method controls correctly. Some methods have secret codes in them, which you don't want to give access to your developers, then you can set it private. We will cover such things in detail later, let's first have a look at Introduction to Methods in C#:
Introduction to Methods in C#
- Methods in C#, also called Functions, are extremely useful in optimizing the code, normally used to create a logic once and use it repeatedly.
- It happens in projects where you need to do a similar job at various places of your code.
- In such conditions, it's wise to create a small function of your repeated code and instead of adding those lines again and again, simply call the function.
- Here's the syntax of Methods in C#:
Access-Modifiers Return-Type Method-Name ( Parameters ) {
// Method-Body
}
public void HelloWorld(){
Console.Write("Hello World !!!");
}
- Access-Modifiers: Access Modifiers are used to control access capability of any method / function. You can set them public, protected or private etc. We will discuss them later in detail.
- Return-Type: It decides what the method is gonna return, it could be void or any data type i.e. int, float, string etc.
- Method-Name: It's the unique name of the Method / Function, which can't be any reserved keywords in C#. It's should be meaningful so you can remember later.
- Parameters: Parameters are optional and are normally used to transfer data between methods.
- There are two types of methods available in C#, which are:
- Instance Method.
- Static Method.
- Let's discuss both of them separately, in detail:
Instance Method in C#
- Those methods, which doesn't have static keyword in their definition are called Instance Methods in C#.
- In order to call instance method in another method, we have to first create a new instance of that method and the invoke the method using dot operator.
- Let's have a look at how to create and call an instance method in C#:
- You must have realized by now that all the work we have been doing so far was in Main Method. That's the default method, the C# compiler first goes into and it's a static method as it has static keyword in it, which will discuss next.
- So, now in above figure, I have created a new method and I have used public (access-modifier) and void (return-type) and the Method-Name is PrintNames. I am using studentsNames array as a parameter.
- I have used the same code which we have designed in our previous lecture on For Loop in C#, so I have placed the foreach loop in my newly created instance method named PrintNames.
- Now in order to call this new method in Main method, I have to first create a new instance of this method's class and you must have noticed that the class name is Program at the top.
- Both of our Main & PrintNames Methods are placed inside Program class.
- So, in our Main function, I have first created a new instance of my class Program using new keyword:
Program P = new Program ( );
- After that, using this class instance P, I have invoked the PrintNames method using dot operator ( . ).
P.PrintNames ( studentsNames ) ;
- When you are calling your method, make sure you enter the parameters correctly as specified in its definition otherwise compiler will generate an error.
- You can specify multiple parameters separated by commas.
- So, that's how we can create and call an instance method, so now let's have a look at How to call static method in C#.
Static Method in C#
- Those methods, which have static keyword in its definition are called static methods in C#.
- In order to call a static method, we don't need to create a new instance of Program class.
- Instead, we can directly invoke a static method from Program class using dot operator ( . ), as shown in below figure:
- In above figure, I have created a new method called PrintNames2 and I have used static keyword in its definition, so its a static method in C#.
- So, now in order to call that method, I have used the name of class and then invoked the method using dot operator, using below code:
Program.PrintNames2 ( stringNames );
- We don't need to create a new instance of class for static method, that's the difference between static and instance methods in C#.
So, that was all about Methods in C# and I hope you have understood the difference between static and instance methods and how to invoke them. In the next lecture, we will have a look at Introduction to Namespace in C#, which is another important concept in C#. Till then take care & have fun !!! :)