List of Posts under C#

This is a list of of posts written under the category C# . Scroll down to see all the posts. They have been ordered by the date of publish.
(Rev. 03-Dec-2022)

Categories | About |     |  

List of Posts

This is the complete list of categories of posts written under the category C# . They have been ordered by the publish date, with the most recent first.

  1. Published: 27-Oct-2022
    Discards are denoted by an underscore. They can be thought of identifiers that receive an assignment, but the assignment is discarded and not available for use. A discard is most commonly used to indicate that the return type of a function has been ignored intentionally. But there are other less known use-cases of a discard. This tutorial demonstrates them by using various program examples - using a discard to (1) ignore a function return, (2) ignore the return of a tuple, (3) ignore an out parameter of a function, (4) default case of a switch expression and (5) as a forced assignment.


  2. Published: 26-Oct-2022
    This tutorial continues from the previous tutorial where we created a database and a table in it. We shall now add a blog record to the table and save it. Then we shall extract it back and make a change to the Heading property, and save it again. Then we shall extract it back and delete it from the table. Finally, we shall display the count of records in the table, and verify that it is shown zero.


  3. Published: 25-Oct-2022
    Create a list of Category records with ID and Name as properties. Add 3 items to this list - (ID:1, Name:"For Men"), (2, "For Women") and (3, "For Kids"). Then create a list of SubCategory records with ID, Name and CategoryFK as properties. The property CategoryFK is a foreign key for the ID property of a Category. Add these items - (ID:1, CategoryFK:1, Name:"Shirts"), (2, 1, "T Shirts"), (3, 1, "Trousers"), (4, 2, "Skirts"), (5, 2, "Shoes"). Use the GroupJoin extension to present dresses of men under a heading "For Men", dresses of women under "For Women" and likewise for kids.


  4. Published: 24-Oct-2022
    Database connectivity is required in almost every project. It is best done with the help of EF Core libraries. The good thing is that the steps for database connectivity are fairly standardized now. The same steps are used for C# console applications, the same are for a C# winforms, C# WPF and even C# web applications. This tutorial walks you through the steps required for creating a database. In the next tutorials we shall explain the create, read, update and delete operations.


  5. Published: 22-Oct-2022
    Two lists can be joined on common key or keys by using the Join extension method. The concept of a join in linq is exactly the same as in SQL of databases. A detailed concept of joins is far too complex to be described in a single tutorial. So this tutorial has been kept simple to help you get started and walk you to a point where a further study is easier.


  6. Published: 21-Oct-2022
    C# Linq provides a GroupBy extension method for grouping records on a common key. This tutorial starts with a brief introduction to the concept of grouping. Then we use the GroupBy extension to group various records on a property called last name so that customers of the same last name are grouped together. The result is then displayed on console.


  7. Published: 19-Oct-2022
    In this tutorial we learn about FirstOrDefault, Single, First and SingleOrDefault extension methods available on an IEnumerable. Use FirstOrDefault for finding the first element that matches a condition. It returns the default value if no matching records exist. "First" does the same thing but throws an exception instead. SingleOrDefault returns the default value if exactly one record cannot be found. There is one more called Find which should be used if the search has to be by a primary key value.


  8. Published: 19-Oct-2022
    In this tutorial we learn the use of Select, Where, OrderBy and OrderByDescending functions provided by C# LINQ. A program has been used to explain these functions. This will help you get started but experience is the best teacher. So all I can help you is get started.


  9. Published: 17-Oct-2022
    This tutorial introduces you to the IEnumerable interface and its practical significance. After that we discuss the internal workings of this interface. We demonstrate how the yield keyword can be used to return an IEnumerable from a function. The tutorial concludes with a C# program to efficiently print a fibonacci series by using the yield keyword and statement.


  10. Published: 16-Oct-2022
    We have to store four properties of a record - student id of string type and marks in three subjects of Int32 type. Inside main create an array of 10 items. Use a for-loop to fill the array. Each item can be filled with random data. Then, use a select query on the array to project two fields only - Student ID and marks in the first subject. Print the queried data with a suitable loop. Use var keyword as far as possible.


  11. Published: 14-Oct-2022
    Create a class called MyNumber with a property called Number of Int32 type. This class should contain an event delegate that takes one argument of Int32 type. The class MyNumber should raise this event when the Number property changes. The changed value should be sent as an argument to all delegates that register to this event. Inside Main create an object of MyNumber and attach an event handler that prints the changed value. The event handler should be an anonymous expression lambda that receives an Int32 argument and prints the number to console. Test the project by changing the Number property. If you did the things correctly, then you should see the event handler called. This might be a difficult one. So please go through the solution if you find the question itself difficult to understand.


  12. Published: 11-Oct-2022
    Create a class MyClock that contains only one public function "void Tick(Object?)". This signature matches the signature of the TimerCallback delegate defined in the System.Threading.Timer class of dotnet. The "void Tick" function prints the current system time on the console (use DateTime.Now). Inside Main create a System.Threading.Timer by using a suitable constructor that calls "void Tick" once every second. Run the program to verify that you have a clock that prints the current system time. You will have to study the documentation of System.Threading.Timer class.


  13. Published: 10-Oct-2022
    This exercise is an exercise just for the sake of practice in static and consts in a class. Create a class called CBankAccount that contains a static member to hold the name of the bank, a constant member to store the minimum balance (100) that a customer has to maintain, another constant member for rate of interest (5) and a yet another constant member for periodicity (4 months) of applying interest. Also add an instance member to hold the balance of a customer in dollars. Add a static constructor to initialize the name of the bank by obtaining input from the user. Add a static function called RenameBank that can be used to give a new name to the bank. Add two functions called Withdraw(int amount) and Deposit(int amount) that update the balance after a successful transaction and print it. Also add a function AddInterest() that calculates simple interest for four months and updates the balance. Test the class in Main.


  14. Published: 10-Oct-2022
    Write a C# class called CData to hold a float type of quantity. This class also contains an enumeration of two members - Meter and Centimeter - to specify the unit of the quantity stored. Add a constructor and a public function called Convert. The Convert function converts the data to meter if the data held is in centimeters, and to centimeters if the data held is in meters. The Convert function displays the result correct to 2 decimal places. Test the function by creating an object in the main function.


  15. Published: 07-Oct-2022
    We expect you have a very general understanding of object oriented programming blocks like classes and structs. In this tutorial we have a quick look at a class in C#. Then we have a discussion of the structs, and then a detailed look on the record keyword. The tutorial closes with "When to use a record".


  16. Published: 04-Oct-2022
    In this tutorial we take a hypothetical problem to build towards the concept of generics. First we explore a few bad solutions. Then we explain a perfect solution by generics. That leads us to list the benefits of using generics. We conclude with the constraints on generic parameters.


  17. Published: 03-Oct-2022
    An interface is a collection of related functionality. An audio player is an audio player only if it implements the ability to play, pause, stop, etc., We can say that the functions play, pause, stop are together an interface called IAudioControls. An interface is a set of functions grouped together under the interface keyword. An interface cannot contain instance data members - they can, however, contain static data members - but that's an entirely different thing because static members are tied to a class or interface, not to a specific object. In this tutorial we examine various aspects of interfaces from C# perspective.


  18. Published: 28-Sep-2022
    Only one copy of a static data member exists in the entire program. A const member behaves like a static, but it's value is marked as fixed and constant. The compiler knows its value. Therefore it can make substitutions and avoid memory allocation for a const member. Let's see the finer details.


  19. Published: 28-Sep-2022
    A static class is a container for self-contained static functions that just operate on the input operators. The concept of a static class and static members is essentially the same as in other object oriented languages like C++ and Java. static classes provide simplicity but they are not a part of pure object oriented design. The general guidelines are to use static classes only SPARINGLY in your projects. In this tutorial we learn about the features of a static class in C#.


  20. Published: 15-Sep-2022
    This tutorial is for explaining a few programs that exhibit the idea of polymorphism. I won't be able to go into the philosophy of polymorphism. The whole point of this tutorial is to introduce you to the syntax, and about how the usual things are done in a C# syntax.


  21. Published: 14-Sep-2022
    Inheritance in C# is similar to what we have in other object oriented languages. In this tutorial we take a short example to get introduced to the syntax. We also learn about the protected and sealed keywords.


  22. Published: 13-Sep-2022
    In this tutorial we learn about delegates that are a data-type for a function signature. In this context a function signature includes the return type and the arguments of a function, but doesn't include the name. We also learn about lambda expressions and built-in delegates called Action and Func delegates.


  23. Published: 12-Sep-2022
    Functions in C# are usually called Methods. They can exist inside a class, struct, record - but not globally outside. So every function, including the Main function must be declared inside a class or a struct. In this tutorial we examine default arguments, named arguments, passing parameters by value and reference, the use of in keyword and finally passing unspecified number of arguments with the params keyword.


  24. Published: 11-Sep-2022
    An anonymous type is described by a comma separated properties clubbed into curly braces. The properties are readonly. The corresponding data-type is generated by the compiler. The name of the data-type remains unknown. It is not accessible in source code. Such types are called anonymous types. They are used to quickly store data without the need of defining a data-type. They are also used in query expressions.


  25. Published: 08-Sep-2022
    Value Types and Reference types are two types in C#. If you are familiar with C and C++, then you can think of reference types as that hold address of objects created on a heap memory. In contrast the value types hold an object. These concepts are far too complex for a beginner's tutorial. So I will try to explain them from a practical standpoint.


  26. Published: 05-Sep-2022
    The concept of a property is the most widely used in dotnet programming. Properties provide setter and getter functions for validation of data before it enters or leaves your object. A property has a specific syntax that needs to be mastered.


  27. Published: 04-Sep-2022
    Main method is the equivalent of the main method as we know in C language. It's the entry point of your program which means that it is the first function that executes when your program starts its execution. In this tutorial we learn the syntax of this function; we also learn about top-level statements that provide a shortcut to the main function.


  28. Published: 01-Sep-2022
    An object reference might be null when your code calls a function or accesses a property. Programmers use an if-condition as a safety net and make a null-test on an object that has a possibility of being null at that point. The null conditional operators make it easier to write the code without the if-condition.


  29. Published: 31-Aug-2022
    If a function consists of only one statement or expression, then the braces and the return keyword could be redundant. Thus, we can simplify such functions by removing the braces and the return keyword. The result is that the overall look of the function becomes simplified, and it becomes easier to read. Functions, properties, operators, and indexers that use this syntax are called expression-bodied members.


  30. Published: 29-Jun-2022
    If you already know of the Task type, and have now happened to meet a similar looking ValueTask, then you are likely interested in knowing more about these types, and this article is my attempt at a quick explanation of the relation between ValueTask and Task types.


  31. Published: 23-Nov-2021
    Following are some of the reasons that you can consider when deciding on learning ASP.NET Core. I think .NET Core has a good future and in the coming days it is about to become the default web development technology. Write to us if you have something to add!


  32. Published: 26-Aug-2021
    This tutorial continues from where we left the tutorial on INSERT query (see the link below for a recap). The code we discussed there has been extended to display the inserted data. In the first part of this tutorial we explain the minimal three basic things that must be done to display data on a razor page. Then we incorporate those additions into the index page and its backing class to show the whole idea in action.


  33. Published: 24-Aug-2021
    This article explains behind-the-scenes mechanism by which "Session" is implemented in ASP.NET Core. We also enumerate the four extension methods that ASP.NET Core provides for reading and writing session variables. After that we present a walkthrough where existence of a Session key is checked to conditionally show a login link, or to show her user-name along with a log-off link that clears the user-name from the Session cache.


  34. Published: 23-Aug-2021
    So this article starts by explaining the various aspects of a partial view from a practical, day-to-day perspective. We have totally removed those parts that are either redundant or too complicated to be of any use for a practical developer. Then we take a small 3-step walkthrough that shows how to create a partial view, and how to consume it in a razor page. We also explain how a conditional menu can be conveniently implemented using the ideas of partial views. Partial Views + Razor Components can add to the confusion of a developer, so we finally conclude with a comparison with razor components.


  35. Published: 18-Aug-2021
    Razor components are stand-alone, embeddable units that replace themselves with pure HTML, CSS and JS markup. They can accept parameters from the host page. We discuss below how they differ from partial pages, and we also discuss the structure of a component page, and also how to use the <component> tag to easily embed a component into a razor page.


  36. Published: 16-Aug-2021
    This is a comprehensive discussion on the need for "areas", and how to practically create "areas", and how, un-like classic MVC, routing occurs out-of-the-box when razor pages are used. We also discuss how tag helpers help us create proper anchor links to pages inside areas. In the end we present a practical login and authorization scheme for projects that use areas.


  37. Published: 15-Aug-2021
    _ViewImports.cshtml is shared by all the razor pages in its peer directory, and in the sub-directories below it. It is like an include file, and it is used to type a list of common directives that would otherwise have to be typed in each of the razor pages. A razor page takes into account the entire hierarchy of _ViewImports files above it.


  38. Published: 14-Aug-2021
    This is a walkthrough on how to obtain user consent for usage of cookies on an asp.net core website. This project uses the ITrackingConsentFeature interface to determine if the user has already given his consent, and also to obtain the correct cookie string as per the http format. The readymade functions of this interface make it extremely easy for a developer to obtain a user's consent.


  39. Published: 13-Aug-2021
    We start this walkthrough with a small introduction to the concept of a cookie, and then we explain the various ASP.NET Core snippets to (a) create a cookie, (b) read a cookie and (c) delete a cookie. And lastly, we create a fully functional application for creating and deleting cookies. You can run the application to see the whole concept in action! We strongly recommend that you watch the linked video for finer details.


  40. Published: 12-Aug-2021
    A form of only one input textbox is POSTed and the data is inserted into a sqlite database. This is a six step walkthrough that starts from creating a model, followed by a DAL based on the DbContext class. We also explain how an application is configured for dependency injection of the DbContext, and also, how the DbContext is extracted from the constructor of a PageModel class, and ultimately used to run a database query.


  41. Published: 08-Aug-2021
    Here is a to-the-point tutorial on how database connectivity works in ASP.NET Core. A 3-step roadmap is laid for running your first query to a database of your choice. The tutorial concludes with an example walkthrough on adding nuget packages for a sqlite database. The actual database connectivity is done in later tutorials.


  42. Published: 07-Aug-2021
    This is a walkthrough on how to make calls to an XML database via repository pattern and dependency injection. We also give a brief introduction to the repository pattern and dependency injection, and also explain the associated benefits.


  43. Published: 06-Aug-2021
    This is the simplest example of reading and updating a record. For simplicity, the record consists of just one property called Name. An input textbox is used to display the "Name" and the same textbox is used to post the updated value. Reading and writing is done with the built-in XMLSerializer class.


  44. Published: 05-Aug-2021
    Looking for the "protected" App_Data folder in ASP.NET Core? The news is that it doesn't have that status anymore. It is no longer a "Special" folder. However, a workaround exists, and I demonstrate it in this tutorial. This tutorial explains how to read the contents of a notepad file (located in a "protected" folder of any random name). The contents are read from within the application, and displayed. Later we verify that the same notepad file cannot be accessed from the browser. This concept can easily be extended to use XML as a database, a topic we shall explore in some future posts.


  45. Published: 25-Mar-2021
    Anti-forgery token is NOT available outside of <form> tags. This article, alongwith the appended video, explains how to use IAntiforgery service to solve this limitation, and POST data, especially as an AJAX request, when a full-fledged form is not possible?


  46. Published: 23-Mar-2021
    Following are my top 6 interview questions on the "init" accessor introduced recently in C# 9. The answers have all been fully explained through code examples. All the examples have been kept as short as possible.


  47. Published: 22-Mar-2021
    Simplest explanation of AJAX based Edit, Update, Cancel operations on a row of an HTML table. An ASP.NET Core POST handler receives the updated values that can be processed for an update to a database.


  48. Published: 16-Mar-2021
    In brief: Just two additions are required to implement AJAX based authorization in your existing ASP.NET Core application - first is on the javascript side - where the response code should be tested, and second on the server side where User.IsInRole has to be tested. The concept is explained in the text that follows, and a working example is described in the appended youtube video!


  49. Published: 12-Mar-2021
    THE CRUX: record types are meant for storing read-only, init-once data. They serve the purpose of ValueTypes, but in reality they are reference types; they have best of both the worlds. They, being reference types, can be efficiently passed as function arguments(like class objects), and yet they carry data like structs [though read-only] but the data doesn't get copied during function calls - this promotes efficiency. They are 2-in-1: they are RefTypes but they perform the task of ValueTypes (though read-only, init-once). So with C# 9.0 we have a triad - class, struct and record. Two different instances of records are equal if they contain the same data (like structs, and un-like the classes!) The "positional record" syntax makes it easier to create their objects, and the newly introduced "with" expressions make it even easier to create their exact copies, possibly with just-in-time alterations to some of their properties.


  50. Published: 11-Mar-2021
    This project is about creating an Admin Panel that would be suitable for a reporting project or an EBook that shows a table of links on the left and the corresponding content on the right side. The content is obtained by an Ajax call to an ASP.NET Core application. Source code for all the three files has been given and explained below.


  51. Published: 09-Mar-2021
    In nutshell: The selection change event of the master dropdown is used to send the "id" of the selected item to the server, which sends back a collection of items for the slave dropdown. A javascript based Ajax GET request is used for this communication with the server.


  52. Published: 05-Mar-2021
    The following project has a textbox with a send button. The click event fires an AJAX GET request and sends a string parameter to an ASP.NET Core application, which responds by converting the parameter to its uppercase equivalent. The client side script has been written using pure javascript.


  53. Published: 03-Mar-2021
    How to POST an ASP.NET Core Razor FORM through an Ajax Request. We discuss a practical approach that is to-the-point and easy to understand. The given code is ready to copy-paste!


  54. Published: 27-Sep-2020
    Some, not all, routes need a daily downtime between 17 hrs to 18 hrs. So they have to be shut during that period so that no requests are processed. Any request has to be redirected to another page or a website, say, hoven.in. How should that be implemented?


  55. Published: 25-Sep-2020
    Write an ASP.NET Core application such that the route "/home/index/N", where N is any int number, executes only if the website is hosted on port 67291 of "hoven.in" or "www.hoven.in". It should return 404 even if it is hosted on any subdomain like "*.hoven.in:67291"?


  56. Published: 23-Sep-2020
    This is a summary of the concepts of routing and route templates in asp.net core. We have taken a practical exercise to develop the concepts in an interesting way.


  57. Published: 18-Sep-2020
    Use the concepts learnt till now, and without using razor, and without mvc framework, create a contact form that has a text box (cusName) and a date picker (meetOn), and that posts data to your asp.net core application. The application echoes this data back to the browser.


  58. Published: 16-Sep-2020
    This tutorial explains everything necessary to get you started with the middleware in ASPNET Core. We explain the built-in middleware components as well as the Use, Map and Run extension methods through practical code.


  59. Published: 03-Sep-2020
    This tutorial explains the Startup class in ASP.NET, along with the methods of this class. We also explain how a custom middleware can be attached by IStartupFilter.