Dependency Injection in ASP.NET Core
Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at Dependency Injection in ASP.NET Core. It's our 7th tutorial in ASP.NET Core series. In previous versions of ASP.NET, dependency injection was not its core element, although we could have achieved it using third party packages i.e. Ninject, StructureMap etc.
As ASP.NET Core is built from scratch so it was made sure that Dependency Injection should become its essential part. In our previous lecture, we have created Controller & Model for our core project. Now there's a need to connect them together and that will be done by Dependency Injection. So, let's get started with Dependency Injection in ASP.NET Core:
Dependency Injection in ASP.NET Core
- Dependency Injection in ASP.NET Core is used to inject dependencies in Web Application and these dependencies are mentioned in IoC Container, implemented by IServiceProvider.
- In Startup.cs file, the ConfigureServices Method is dependency injection container and if you check it's parameters, then you will find IServiceProvider in it.
- There are different types of Dependency Injections available and the most commonly used one is Constructor Injection.
- In our Startup.cs file, we have seen two Methods: ConfigureServices and Configure.
- So far, we have only discussed Configure Method, which is used to set up Request Processing Pipeline and we add our Middlewares in it.
- But we haven't yet discussed the ConfigureServices Method, which is an IoC Container and is used for service configuration required by our application.
- We can configure both builtin and custom services in this ConfigureServices Method.
- In our previous lecture, we have added an MVC Service (builtin) in this IoC container, as shown in below figure:
- Similarly, we can also create custom dependencies in ASP.NET Core and these custom dependencies will also be registered in this ConfigureServices Method.
- In our previous lecture on MVC architecture, we have created an Interface named IEngineersRepository and a class implementing this interface named EngineersRepository.
- In our future coding, we will never invoke this class, as its an implementation and we don't want to directly call this class as it will make our code rigid. Instead, I will always call this Interface as it's just a definition. ( If you are not getting this point yet, don't worry we will cover it in detail later)
- So, now we have to insert this dependency so that if someone wants to use any method from Interface IEngineersRepository, compiler should know that it has to invoke the method from class EngineersRepository, without actually calling the class.
- So, let's add this dependency using AddSingleton Method, as shown in below figure:
- You can see in above code that in a single line, we have declared our dependency i.e. our interface IEngineersRepository is dependent on class EngineersRepository.
- Now in our project, whenever we invoke this interface IEngineersRepository, compiler will know that I have to look in EngineersRepository class.
We have added the dependency condition in our Dependency Injection Container. But remember one thing that we haven't yet connected Model and Controller. We have just connected a Model Class with a Model Interface. So, now let's have a look at Constructor Injection in ASP.NET Core:
Constructor Injection in ASP.NET Core
- When we want to inject one service into another then we use Constructor Injection in ASP.NET Core.
- The service, we want to inject, is provided as a parameter to the Constructor of the service, in which it is being injected.
- In our example, we want to inject our Interface IEngineersRepository in our Home Controller so that we could use its methods, as shown in below figure:
- I have encircled the constructor injection code with red line, and you can see that I have created the Constructor of Home Controller and then passed interface as a parameter.
- Finally, simply saved the value in private variable _engineersRepository.
- In the action method index(), I have used this variable and then called the method GetEngineers, which is implemented in my class and will provide me the data based on Id, which I have provided 1. ( Rite now value is hard coded, we will automate it soon )
- So, I am getting the university name of engineer with Id = 1, and if you remember we have hard coded the data and the university of first student was MIT.
- So, now let's run this project and if everything goes fine then you will get similar results:
- So, let's summarize our lecture, we have used dependency injection and then called Model function from home controller.
Why we need Dependency Injection ???
- When you are working on some complex application, then we want it to be as flexible as we can and here dependency injection comes quite handy.
- With Dependency Injection, we can bound different parts of our application together.
- Let's say you have created some Interface named "IEngineersData" and then a class implementing it named "EngineersProfile".
- Now in order to implement Constructor Injection, you first have to configure it in the ConfigureServices Method so that compiler could know that this class is implementing that interface.
- In future, if you want to change the implementation of your Interface, you just need to change the name in this IoC Container.
I know it's not making much sense rite now and is a bit difficult to understand, but no need to worry as in our upcoming lecture, we will have a look at practical implementation of these concepts. So, that's all for today, in our next lecture, we will have a look at Views in ASP.NET Core. Till then take care & have fun !!!
Environment Variables in ASP.NET Core
Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to use Environment Variables in ASP.NET Core. It's our 5th tutorial in ASP.NET Core series. In our
Startup.cs file, you must have seen that we have an IF Condition at the start and this IF Condition has
IsDevelopment in it.
This condition is actually checking the environment of our web application. So, here we will first discuss them and then will see why we need them. So, let's get started:
Environment Variables in ASP.NET Core
- ASP.NET Core has 3 builtin Environments, which decides the Run-time operating environment of the web application, which are:
- Development.
- Staging.
- Production.
- In order to set this Environment Variable, we need to open the launchSettings.json file, in the Properties section of Solution Explorer.
- This launchSettings.json file has two profiles in it and both of these profiles have a variable ASPNETCORE_ENVIRONMENT, this variable is used to set the Environment value.
- In the above code, you can see that we have set the value of ASPNETCORE_ENVIRONMENT to be Development, that's why we are in Development mode.
- Let's discuss these 3 environment variables one by one:
Development Environment
- As the name implies, when we are developing the application then we are in Development Environment, so the value of this variable should be Development.
- In Development mode, we can show many details for understanding which we can't directly show to our end user.
- At the start of this Configure Method, you must have seen IsDevelopment, its a builtin ASP.NET Core Boolean function, which is checking the Environment.
- If the Environment is Development then show the Developers Exception Page and as this page has a lot of useful information, we can't show this information to our user, it will be dangerous.
- That's why, we have placed this check that if we are in the Development Environment, only then show this Exception Page. ( We will discuss Exception Page later in detail )
Staging Environment
- When you are developing complex cloud platform web application, then before transferring it to Production Environment, you first have to test it out in Staging Environment.
- Staging Environment is quite equivalent to Production Environment and is normally for QA purposes to have a final look before publishing.
- You can also use IsStaging function just like IsDevelopment in ASP.NET Core.
Production Environment
- When you are fully confident that your application is complete and follows all security protocols etc. then you can set the Environment to Production.
- If you remove this ASPNETCORE_ENVIRONMENT code line from the lauchSettings.json file, then by default, the runtime Environment is Production.
- We also have IsProduction function to use in ASP.NET Core.
Custom Environment
- We can also create a new custom environment in ASP.NET Core, we just need to specify this new name i.e. TEP in the launchSettings.json file.
- Now, in order to check the custom environment, we need to use IsEnvironment("TEP") function, as shown in the code on right side.
- We can use any name for this custom environment, we need to use custom environments in such application where we need to use separate profiles i.e. teacher, student, parents etc.
Developer Exception Page Middleware
- As we have discussed the Environments, so now let's have a look at this Middleware Developer Exception Page.
- It's another builtin ASP.NET Core Middleware, which shows an Exception Page to the Developer, if there's any exception occurs in your application.
- This exception page is very helpful, as it gives detailed information about the exception or the issue occurred in the application.
- We don't want to show this Exception Page to our end user as it reveals a lot of information related to our app, which could be helpful in hacking stuff.
- So, that's why we have placed it inside IsDevelopment condition.
So, that was all about Environment Variables in ASP.NET Core. In the next tutorial, we will have a look at MVC architecture in ASP.NET Core. Till then take care & have fun !!! :)
How to handle Static Files in ASP.NET Core
Hello friends, I hope you all are having fun. In today's tutorial, we are going to have a look at
How to handle Static Files in ASP.NET Core. It's our 4th tutorial in ASP.NET Core series. If you inspect your localhost page displaying Hello World, then you will see that there isn't any HTML code in it. Instead, it's just displaying Hello World in text format.
In today's tutorial, we will have a look at How to add HTML, JavaScript, CSS or any other static file in ASP.NET Core. In our previous tutorial, we have discussed
Middleware in ASP.NET Core, so if you haven't studied that then have a look at it first, as we are gonna use some new middleware components today. So, let's get started:
How to handle Static Files in ASP.NET Core
- By default, ASP.NET Core doesn't allow us to handle / serve static pages and we can add this functionality using Static File Middleware.
- In the Solution Explorer, right click on your Project's Name and then click on Add > New Folder and rename it to wwwroot, as shown in below figure:
- All the static files ( JavaScript, CSS, HTML, Images etc. ) in ASP.NET Core has to be placed inside this wwwroot folder, which is called Content Root Folder, and this folder has to be directly inside the project's root folder i.e. Project's Name.
- Now let's create three folders inside this wwwroot folder for CSS, JavaScript & Images, as shown in below figure:
- In the above figure, you can see that I have created three folders and have also added an image in the images folder.
- You could change these folders' names but its a convention to use these names, it helps in keeping things organized.
- So, now let's access this image in the browser i.e. open this link http://localhost:51640/images/image1.jpg but still you won't get the image, instead it will still display Hello World.
- In order to access this static file i.e. image1.jpg, we have to add a new middleware in the request processing pipeline.
- So, open your Startup.cs file and in the Configure Method, add Static Files Middleware, as shown in below figure:
- You can see in above figure that I have added app.UseStaticFiles() middleware, it's a builtin middleware of ASP.NET Core, which enables the web App to use static files in wwwroot folder.
- After adding this Middleware, now when you open your image link then you will get your image in the browser, as shown in below figure:
Default Home Page in ASP.NET Core
- We can also create a default HTML Home Page in ASP.NET Core using a builtin middleware Default Page.
- This Default Page middleware search for one of the following files in wwwroot folder:
- index.htm
- index.html
- default.htm
- default.html
- If the middleware finds any of the above titled files in wwwroot folder, it will make that file default page or homepage.
- So, let's first create an index.html file in the wwwroot folder, as shown in the image on right side.
- In order to add this index.html file, right click on wwwroot folder and then Add > New Item.
- In the next window, make a search for html page and rename it to index.html.
- Here's the code for that HTML file, I have just added the required HTML along with an H1 tag.
- Now let's add the Default Page Middleware in our Configure Method in Startup.cs file.
- The Configure Method is shown in figure on right side & you can see that I have removed the End Points Middleware.
- Moreover, I have added a new Default File Middleware before Static File Middleware.
- This Default File Middleware doesn't serve the default file itself, instead it just change the request path towards default file, this file is then served by Static Files Middleware, next in the pipeline.
- So, if you place this Default Files after Static Files, then it won't work because files are served first and then default path is set. So, again emphasizing on this point: Position of Middleware matters a lot.
- So, now if you run your web Application, then you will get this index.html file as home page, shown in below figure:
- Now let's have a look at another ASP.NET Core builtin middleware named File Server Middleware.
File Server Middleware
- File Server Middleware combines the functionality of three middlewares in ASP.NET Core, which are:
- Default Files Middleware.
- Static Files Middleware.
- Directory Browser Middleware. ( it gives us information about directories i.e. file no. etc. )
- You can see in the code that I have removed Default Files & Static Files Middlewares & replaced them with File Server Middleware.
Now let's have a look at How to Customize these Middlewares:
How to Customize Middleware ???
- We have discussed it in Middleware lecture that each Middleware starts with "Use" keyword and they are all extension methods.
- Now, in order to Customize these Middleware objects, we need to use respective Options Objects.
- So, let's change the default homepage file to any other file, here's the code:
- After the Routing Middleware, I have created a new instance of File Server Options.
- You can see that, it has the Middleware Name i.e. File Server & then "Options" keyword.
- Similarly, for Default Files Middleware, we have DefaultFilesOptions object for customization.
- After creating the new instance, I have cleared the default file name first and then added a new file name "tep.html".
- You must have created this HTML file in your wwwroot folder, so that File Server Middleware could access it.
- Finally, I have provided this fileServerOptions object as a parameter to UseFileServer Middleware.
- So, that's how we can Customize our home page as well as middleware.
- So, key point to note here is: Middleware starts with "Use" keyword, while its customizing object ends with "Options" keyword.
So, that was all about How to handle Static Files in ASP.NET Core. In the next lecture, we will have a look at this Developer Exception Page Middleware, present at the start of our request processing pipeline. Till then take care & have fun !!!
Middleware in ASP.NET Core
Hello friends, I hope you all are doing great. In today's tutorial, we are going to have a look at what are
Middleware in ASP.NET Core. It's our 3rd tutorial in ASP.NET Core series. In order to understand the Middleware, we have to open the Startup.cs file present in Solution Explorer.
In our previous lecture, we have discussed the Code in Startup.cs and I have told you thhat we will discuss the Configure method later, so now we have to understand that code first. So, first let's define middleware components and then have a look at that code:
Middleware in ASP.NET Core
- Middleware in ASP.NET Core are simple software components used to control HTTP requests and handle both incoming requests as well as outgoing responses.
- Each middleware is a separate object, has a specific role assigned to it and are placed one after another in the request processing pipeline, as shown in below figure:
- The middleware components are used for different purposes i.e. Authentication, Logging in, Verification, File Upload ( .js, .css ) etc.
- These middleware components operate in fix order from top to bottom, so the incoming request is first received by the 1st Middleware and after proper processing on the request, it is forwarded to the 2nd Middleware.
- A middleware can also skip the request and without any processing, forward it to next middleware.
- For a proper working cloud based web application, we have to add a lot of middleware components, which we will see in coming lectures.
- There are many builtin middleware components available in ASP.NET Core as Nuget packages and we can also design custom middleware components in it.
- So, now let's open the Startup.cs file and have a look at the Configure Method, as shown in below figure:
- You can see in the above code that we have a Startup Class, which has two functions in it, which we have discussed in our previous tutorial.
- So, now let's have a close look at the code in Configure Method, it currently has three middleware components in it.
- The first middleware components is placed inside IF loop and is shown in figure on right side.
- You can see in the IF Loop we have Developer Exception Page, it's a builtin ASP.NET Core Middleware Component.
- By convention, each middleware component start with "Use" word in ASP.NET Core, so if you are designing a custom middleware component, then its better to follow this practise.
- We will study this Developer Exception Page in detail later, but for now you just need to know that its a middle ware component which shows an exception page to the developer and as it's inside IF Loop so it will be available only in Developers Environment, we will study Environment in coming lectures.
- One more thing, we are using app and then dot operator to use Middleware in ASP.NET Core.
- Second Middleware Component is app.UseRouting(), so the middleware name is Routing.
- Finally the third middleware is End Points, which is displaying Hello World! on the page.
- These Middlewares in the Configure Method, collectively create a pipeline structure i.e. there are executing one after another from top to bottom, this pipeline structure is called Request Processing Pipeline.
So, that was all about Middleware in ASP.NET Core. If you got into any trouble, then ask in comments and I will help you out. In the next article, we will have a look at How to add static files in ASP.NET Core. Till then take care & have fun !!!
Create First Web Application in ASP.NET Core
Hello friends, I hope you all are having fun. In today's tutorial, we will create our First Web Application in ASP.NET Core. It's our 2nd tutorial in ASP.NET Core series and in our previous tutorial, we have had a detailed
Introduction to ASP.NET Core.
We have also installed Microsoft Visual Studio Community Edition 2019 in our previous tutorial and today we will create our first web application in it. After creating this web application, we will also have a look at its files and will understand the contents. So, let's create our First Web Application in ASP.NET Core:
Creating Web Application in ASP.NET Core
- First of all, start your Visual Studio which we have installed in previous tutorial.
- A pop up window will open up, where you can open your recent project or can create a new project, as shown in below figure:
- Here, click on the button says "Create a new project" and a new window will open up.
- This new window will ask for the type of application, you want to create i.e. Console App, Web App, Blazer App etc.
- As we want to create an ASP.NET Core Web Application so, I am going to select 3rd option in the list, as shown in below figure:
- After selecting ASP.NET Core Web Application, now click on the Next Button.
- On the next window, we have to provide the name & location for the project, as shown in below figure:
- Now click on the Create Button and in the next window, we need to select the template for your web application.
- Rite now, we are going to select the Empty Project, as I want to start from the scratch but in our incoming tutorials, we will cover almost all these templates.
- You will also need to uncheck the check box says "Configure for HTTPS", as shown in below figure:
- So, select the Empty Template for your ASP.NET Core web application and click the Create Button.
- As you can see at the top of above figure that we are using ASP.NET Core 3.1 that's the latest stable .NET framework SDK.
- When you click on the Create Button, Visual Studio will create your web application, as shown in below figure:
- As we have selected the Empty template, that's why we don't have much files in the solution explorer and this web app won't do anything except printing " Hello World " on execution.
- In order to execute our first web application, we need to click on the IIS Express play button, at the top menu bar.
- Our default browser will open up and Hello World will be printed in it, as shown in below figure:
- The link of this page is localhost:51640, as its on localhost rite now and the its port is 51640.
- We will discuss the flow of How this web app works and what's IIS Express in our coming lectures.
So, rite now we have a simple working web application in ASP.NET MVC which simply prints Hello World. Now let's understand the files automatically created by Visual Studio in Empty Template:
ASP.NET Core Project File
- If we have a look at the Solution Explorer, the we can see that visual studio has created few files for us, as shown in below figure:
- In order to open the project file, we have to right click on the Project's name and then click on Edit Project File.
- A new code file will open up with an extension .csproj, cs stands for C# & proj for project. This file is called the ASP.NET Core Project File.
- In previous versions of ASP.NET, we have to unload our project in order to open this project file but in Core, we can simply click on this Edit option to open Project File.
- If programming language is visual basic, then extension of project file will be .vbproj, vb for visual basic & proj for project.
- The only element we have in our web application's project file is Target Framework and the value we have set is netcoreapp3.1.
- This element, as the name implies, decides the target framework for our app and if you remember, while creating this project, we have selected .NET Core Framework 3.1.
- This value inside Target Framework tag is called Target Framework Moniker (TFM ), so the TFM of .NET Core 3.1 is netcoreapp3.1.
ASP.NET Core Program File
- Next file we are gonna open is Program.cs, its a C# class file, thus has an extension of .cs.
- Now let's have a look at its code:
- As you can see in above code that we have a class named Program and inside this class we have our Main Method.
- This Main Method is the entry point of our compiler i.e. when our web App executed then this Main method is called.
- If you have worked on any previous versions of .NET framework, then you must have seen this Main method there as well, in fact this web App executes as a console application.
- Within this Main Method, we have called CreateHostBuilder Method, its implemented below Main Method and returns an object that implements IHostBuilder.
- We are passing command line arguments to this CreateHostBuilder Method and then building our web host, which is going to host our web application and finally we are running our web app.
- If we have a look at the CreateHostBuilder Method, then you can see that we are using webBuilder Method and then calling the extension Method Startup.
- This WebBuilder Method is responsible for creating the web host on which our web app is going to host.
- This Startup extension method is available in our next file named Startup.cs, so let's discuss it's code:
ASP.NET Core Startup File
- Below Program File, we have Startup.cs file in our Solution Explorer.
- So, let's open this file and here's its code:
- This Startup Class is called by the CreateHostBuilder Method in Program File.
- Inside this Startup class we have two methods, ConfigureServices & Configure.
- ConfigureServices Method is used for the configuration of services, required for our web application.
- Configure Method is used to configure the request processing pipeline for our web application.
- This method has Hello World in it, which is actually printing on the page, we will discuss this method in coming tutorials in detail.
ASP.NET Core launchSettings,json File
- launchSettings.json file is placed inside Properties, so open this file.
- This file is only required for development purposes on the local machine, when we are publishing our web App then we don't need this file.
- This file actually contain the settings for the hosting environment, as shown in below figure:
- You can see in above code that first we have iiSettings and then profiles.
- In profiles, we have two profiles named IIS Express & TheEngineeringProjects, which is also the name of our project.
- When we run our project from visual studio, then this IIS Express profile is called and if you remember, the port number was same as in iisSettings i.e. 51640.
- But if you run this app from Console, then TheEngineeringProjects profile will be called and in that case port number will be 5000.
ASP.NET Core appSettings.json File
- That's the settings file for ASP.NET Core web application.
- We use this file to store some hard coded values or settings etc., we will discuss it in detail later.
So, that was all for today. I hope you have completely understood the basic structure of our ASP.NET Core web application. In the next tutorial, we will have a look at Middleware in ASP.NET Core. Till then take care & have fun !!!
Introduction to ASP.NET Core
Hello everyone, I hope you all are doing great. Today, I am going to start this new series on ASP.NET Core and it's our first tutorial in this series. I will start from basics and will slowly move towards complex concepts. So, if you haven't worked on ASP.NET then you don't need to worry about that but you must have some basic knowledge of C# and object oriented programming.
I will use Visual Studio 2019 for these tutorials, it's community version is free to use and I will use C# language for developing ASP.NET Core web applications. So, let's first have a look at what is ASP.NET Core:
Introduction to ASP.NET Core
- ASP.NET Core (originally deemed as ASP.NET xNext & was going to named as ASP.NET 5) is an open source, modular, cross platform and high performance Framework used to build advanced cloud based Internet Applications i.e.
- Web Application.
- Android Application.
- IOS Application.
- It's built ( rewrite ) completely from scratch by Microsoft & its vast community (as its open source) and combines ASP.NET MVC & ASP.NET Web API in a single package, which were previously available as separate entities.
- Although Core is a completely new framework but still it has quite a lot of resemblance with ASP.NET so if you have already worked on ASP.NET then Core won't be that difficult for you.
- As ASP.NET Core is an open source framework, so you can download or update its code from respective repositories on Github.
Why use ASP.NET Core ?
Let's have a look at few benefits of using ASP.NET Core:
1. Cross Platform
- The first & foremost advantage of ASP.NET Core is Cross Platform accessibility. In ASP.NET, you can only host your application on Windows platform but that's not the case with ASP.NET Core, you can host its applications across different platforms i.e.
- Linux.
- Windows.
- macOS.
- UBuntu.
- Or any self host server.
2. Unified Programming Model
- ASP.NET Core follows Unified Programming Model, that's why both MVC & API Controller classes inherit from single Controller base class, which returns IActionResult.
- IActionResult, as the name implies, is an Interface and has a lot of implementations and two of most commonly used are:
- In case of Web Apis, we get JsonResult and in case of Web MVC we can get both of them.
- In previous versions of ASP.NET, we have separate Controller classes for Web MVC & Web API.
3. Dependency Injection
- ASP.NET Core also has builtin support for dependency Injection, which makes it too flexible and conventional to use.
- Normally we use class constructors to inject dependencies and is called Constructor Injection.
- We will cover them in detail in upcoming tutorials, so if you are not getting this stuff then no need to worry.
4. Modular Framework
- ASP.NET Core also follows modular framework and uses middle-ware components which makes the flow of the app smooth.
- Microsoft has provided a lot of built-in middle-ware components for different purposes i.e. authentication, verification, File Fetching etc.
- We can also create custom middle-ware components as well in AP.NET Core.
5. Open Source
- ASP.NET Core is an open source framework and thus has a vast community on GitHub and Forum etc., that's why it's evolving rapidly and has become extremely powerful.
- You can get detailed and instant help on Core online quite easily.
6. Development Environment
- We can use Microsoft Visual Studio or Microsoft Visual Code for building our ASP.NET Core Applications.
- We can also use third party editors i.e. sublime etc. for ASP.NET Core.
Prior Knowledge Required for this Course
- If you haven't studied ASP.NET then no need to worry as we are gonna start from scratch and will cover all concepts.
- But you must have good understanding of C# concepts, so if you are not that good in C# then you should first read this C# Tutorial.
- Similarly, you should also have some basic knowledge of Html, CSS, Javascript, Jquery, XML etc. These are all simple languages so you must first their basic tutorials as well.
Setting up Environment for ASP.NET MVC
- We can use any Integrated Development Environment (IDE) for ASP.NET MVC i.e. visual studio, visual code, sublime, atom etc.
- We will also need to install .NET Core SDK, which is a software development kit.
- Microsoft Visual Studio Community Edition is free to use and you can download it from its official website.
- Once you downloaded a simple setup of around 1.5MB, you need to run that .exe file and it will start downloading the setup files, as shown in figure on right side.
- Once it's downloaded all the required files to start the setup, a new window will open up as shown in below figure:
- That's called workload area of Visual Studio, here you need to select which tools, you want to install on your machine.
- I am going to select these 3 options from this list:
- As of this tutorial, the latest version available is Microsoft Visual Studio Community Edition 2019 and .NET Framework version is 4.7.2 (latest stable version), which will be automatically installed along with visual studio.
- If you are using any third party editor i.e. sublime, then you need to download the .NET Core SDK and install it on your machine.
- .NET Core SDK is available for Windows, Linux, macOS and Docker.
So, that was for today. I hope you have enjoyed today's tutorial and are ready to get your hands dirty with ASP.NET Core. In our next tutorial, we will create our first project in ASP.NET Core and will write some code. Till then take care & have fun !!!
Introduction to Enums in C#
Hello friends, I hope you all are having fun. In today's tutorial, we will have a look at detailed
Introduction to Enums in C#. It's our 23rd tutorial in C# series and this C# concept is quite easy one. It's normally used to give better meanings/understanding to your project.
If you haven't studied lectures on
C# Classes &
C# Methods, then do read them first, as we are going to use them today. So, let's get started with Introduction to Enums in C#:
Introduction to Enums in C#
- Enums in C# ( short for Enumerations ) is a value type datatype for constants, created by using keyword enum and can be controlled by the class Enum. ( keyword with small e, while class with capital E )
- We can declare & implement Enums directly in C# Namespace, class or struct and the underlying type of an enum is integer.
- Enums are strongly typed so we can't implicitly convert them into any other Data Type. Although we can use explicit conversion to convert enums into integers etc. ( We studied it in Data Types Conversions and we will also look at it shortly )
- Let's understand this enum concept with an example, suppose we are working on some scheduling project and we need to print names of all days.
- As we know these names are constants, and are also occurring in a sequence, so we can create enums for them, as shown in figure on right side.
- There are 3 ways to create Enums as you can see in the figure.
- In the first enum declaration, I have simply added the data in the enum WeekDays. Although, I haven't added any index but still it got the index starting from 0 and then incremented automatically by 1, thorough out the enum, as its underlying type is integer.
- In the second enum declaration, I have added the index in front of the data, so we can do that as well. Although, there's no difference between first & second implementation, its just second one displays the hidden values.
- In the third enum implementation, I have assigned random values to constants, so we can do that as well. Instead of values in a sequence, we can assign random values to these Constants.
Why use Enums in C# ?
- You must be thinking, why we need to use Enums, we can remember such things and can easily replace them with integer checks.
- Yeah we can do that in simple project but in complex projects and especially in those projects where you don't have a sequence, enums play an important role.
- Let's say you need to use Elements of Periodic Table in your project, there are too many elements, so in such cases, enum comes quite handy, you can place these elements in right order in your enum and then can use them easily though out your project.
How to use Enums in C# ???
- Now let's have a look at How to use Enums in C#, so I am creating a simple code where we will check whether it's holiday or working day using enums.
- As shown in below figure, I have created an Enum named WeekDays and this enum is public so we can use it in other classes.
- Moreover, enums are value type so, we can't instantiate them in other classes.
- You can see in above figure that in Main Function, I have created a new variable CurrentDay of Data Type WeekDays, as enum is a Data Type.
- We can't assign any other value to this variable, we can only assign members of its enum to this variable.
- In the IF Loop, I have used the members of enum in my conditions to verify.
- So, now you can see the code has become more Readable & we can easily maintain it without remembering anything.
- We have studied enum keyword so far, now let's have a look at class Enum:
How to use class Enum in C# ??
- In Visual studio, you will also find Enum class along with enum keyword. (enum keyword starts with small e while class Enum starts with capital E )
- We can use this Enum class to get different properties of our enums i.e. we can get their Constants or can also get their underlying integer values.
- We can also search for any keyword in the Enum, whether it exists or not.
- I have performed all these three operations in the code, shown in below figure:
- So, you can see in above figure that we can get Names & Indexes of our enums using this Enum class.
- I have first used the class name Enum, then dot operator and finally methods from Enum Class.
- We can also change the underlying type of our enum using ( : ) colon operator.
- In the right figure,I have changed the underlying type of my enum from integer to short.
So, that was all about Enums in C#. I hope you understood enums & their importance. In next lecture, we will have look at Attributes in C#. Till then take care & have fun !!! :)
Introduction to Access Modifiers in C#
Hello friends, I hope you all are having fun. In today's tutorial, we will have a look at Introduction to Access Modifiers in C#. It's our 22nd tutorial in C# series and now it's time to have a look at access modifiers, which we have to use a lot in C#.
I hope that you have already studied previous lectures i.e. C# Methods, C# Structs, C# Classes etc. as these access modifiers are used with them. So, let's get started with Introduction to Access Modifiers in C#:
Introduction to Access Modifiers in C#
- Access Modifiers in C# are used to apply restrictions on the accessibility of C# Objects within or outside the project, and are defined in the declaration.
- There are 5 Access Modifiers available in C#, whcih are:
- Private
- Public
- Protected
- Internal
- Protected Internal
- We will have a look at all of them, in detail but before going any further, we need to understand the difference between Types & Type Members.
- All those C# objects, which can contain members in them as called Types i.e. C# Classes, Structs, Interface, Enums etc.
- While the members of these types are called Type Members i.e. C# Fields, C# Properties and C# Methods.
- All the C# Types can only be either Public or Internal i.e. we can't make a class private. ( We will discuss it in detail shortly )
1. Private - Access Modifier in C#
- Private Access Modifier restricts the C# Type Members to be used in the containing class only. ( Containing Class means, the class in which they are created )
- We can't use Private Members in external classes, as shown in the figure on right side.
- I have created a Private variable in a new class and now when I am trying to access this variable in Main function, I am unable to do that.
- In the IntelliSense, there's no property/option to use this private variable.
- Although, we can use this variable Number1 in HelloWorld class quite easily.
2. Public - Access Modifier in C#
- Public Access Modifier removes all restrictions from C# Objects and these objects become available in any assembly or project.
- In order to use Public Objects, we need to follow the proper way i.e. we need to instantiate in order to get the Public Property.
- In the figure, you can see I have created a public variable Number1 in a new class and then I have assigned a value to it in my Main Method.
3. Protected - Access Modifier in C#
- Protected Access Modifier restricts the C# Type Members to use only in containing classes or inherited classes.
- We can't use Protected Members in any independent Class or Struct, it has to be inherited from the Containing Class.
- Here's an example of Protected Access Modifier in action, and you can see that I can assign value to Protected variable Number1 in the inherited class HelloWorld2.
- But the independent class Program can't access this Number1 variable.
4. Internal - Access Modifier in C#
- Internal Access Modifier restricts the C# Objects to be used in the current assembly only.
- In complex projects, we need to add multiple assemblies i.e. different add-ons and plugins etc.
- So, Internal variables can be used in the current assembly / project only, we can't access it in external assemblies.
- We will look at them in detail, in our coming lectures.
5. Protected Internal - Access Modifier in C#
- Protected Internal Modifier allows the C# Type Members to be accessed in the containing assembly as well as in those classes ( of external assemblies ), which are inherited from the containing class.
- When we will be done with these basic concepts in C#, then we will design few complex projects and then you will get better understanding of these access Modifiers.
So, that was all about Access Modifiers. In the coming lecture, we will have a look at Enumerations in C#. Till then take care & have fun !!! :)
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 !!! :)