Raihan Taher


Interfaces

A class is a blueprint, which means it contains the members and methods that the instantiated objects will have. An interface can also be categorized as a blueprint, but unlike a class, an interface doesn’t have any method implementation. Interfaces are more like a guideline for classes that implement the interface.

The main features of interfaces in C# are as follows:

  • Interfaces can’t have a method body; they can only have the method signature.
  • Interfaces can have methods, properties, events and indexers.
  • An interface can’t be instantiated, so no object of an interface can be created.
  • One class can extend multiple interfaces.

One of the major uses of an interface is dependency injection. By using interfaces, you can reduce the dependencies in a system.

Let’s look an example of an interface

In the preceding example, we can see that we have one interface, called IBankAccount, that has two members: Debit and Credit. Both of these methods have no implementations in the interface. In the interface, the method signatures are more like guidelines or requirements for the classes that will implement this interface. If any class implements this interface, then the class has to implement the method body.

This is a great use of the OOP concept of inheritance. The class will have to give an implementation of the methods that are mentioned in the interface. If the class doesn’t implement any of the methods of the interface, the compiler will throw an error that the class has not implemented all the methods of the interface. By language design, if an interface is implemented by a class, all the members of the interface must be taken care of in the class.


Abstrac Class

An abstract class is a special kind of class that comes with the C# programming language. This class has similar functionalities to an interface. For example, an abstract class can have methods without implementation and with implementation. Consequently, when a class implements an abstract class, the class has to override the abstract methods of the abstract class. One of the main characteristics of an abstract class is that it can’t be instantiated. An abstract class can only be used for inheritance. It might or might not have abstract methods and assessors. Sealed and abstract modifiers can’t be placed in the same class, as they have completely separate meanings.

Let’s take a look at an example of an abstract class

In the preceding example, we saw that the Dog class is implementing the Animal class, and as the Animal class has an abstract method called Move(), the Dog class must override it.


Partial Class

You can split a class, a struct, or an interface into smaller portions that can be placed in different code files. If you want to do this, you have to use the keyword partial. Even though the code is in separate code files, when compiled, they will be treated as one class altogether. There are many benefits of partial classes. One benefit is that different developers can work on different code files at a time. Another benefit is that if you are using autogenerated code and you want to extend some functionality of that autogenerated code, you can use a partial class in a separate file. Consequently, you are not directly touching the autogenerated code, but adding new functionality in the class.

The partial class has a few requirements, one of which is that all classes must have the keyword partial in their signatures. All the partial classes also have to have the same name, but the file names can be different. The partial classes also have to have the same accessibility, such as public, private, and so on. This will increase the readability of your code, and your code organization will be more structured.


Sealed Class

One of the principles of OOP is inheritance, but sometimes you may need to restrict inheritance in your code for the sake of your application’s architecture. C# provides a keyword called sealed. If this keyword is placed before a class’s signature, the class is considered a sealed class. If a class is sealed, that particular class can’t be inherited by other classes. If any class tries to inherit a sealed class, the compiler will throw an error. Structs can also be sealed, and in that case, no class can inherit that struct.

If we try to create a Dog class that will inherit the Animal class, as in the following code, then the compiler will throw an error “Dog: can not derive from sealed type Animal”, saying that the sealed Animal class can’t be inherited.


Tuples

A tuple is a data structure that holds a set of data. Tuples are mainly helpful when you want to group data and use it. Normally, a C# method can only return one value. By using a tuple, it is possible to return multiple values from a method. The Tuple class is available under the System.Tuple namespace. A tuple can be created using the Tuple<> constructor or by an abstract method named Create that comes with the Tuple class. You can fix any data type in a tuple and access it using Item1, Item2, and so on.


Properties

For security reasons, all the fields of a class shouldn’t be exposed to the outside world. Consequently, exposing private fields is done by properties in C#, which are members of that class. Underneath the properties are special methods that are called accessors. A property contains two accessors: get and set. The get accessor gets values from the field while the set accessor sets values to the field. There is a special keyword for a property, named value, this represents the value of a field. By using access modifiers, properties can have different access levels.

A property can be public, private, read only, open for read and write, and write only. If only the set accessor is implemented, this means that the only write permission is given. If both set and get accessors are implemented, this means that both read and write permissions are open for that property. C# provides a smart way of writing setter and getter methods. If you create a property in C#, you don’t have to manually write setter and getter methods for a particular field. Consequently, the common practice in C# is to create properties in a class, rather than creating fields and setter and getter methods for those fields.

The convention is that properties should be in camel case. When you create a property in camel case, a field with the same name is created internally, but in Pascal case. The value is a special keyword that actually represents the value of that property. Properties are working behind the scenes in the background, which makes the code much cleaner and easier to use. It’s very much recommended that you use properties instead of local fields.


Acces Modifiers for Classes

Access specifiers, or access modifiers, are some reserved keywords that determine the accessibility of a class, method, property, or other entity. The object oriented principle of encapsulation is achieved by using these
access specifiers in C#. In total, there are five access specifiers.

Public

The public access specifier means that there is no limitation to access the entity being modified. If a class or member is set as public, it can be accessed by other classes or programs in the same assembly, other assemblies, and even other programs that are installed in the operating system that the program is running in. Normally, the starting point of an application or main method is set as public, meaning that it can be accessed by others. To make a class public, you just need to put a public keyword before the keyword class.


Private

The private specifier is the most secure access specifier available in the C# programming language. By setting a class or member of a class as private, you are determining that the class or the member won’t be allowed to be accessed by other classes. The scope of a private member is within the class. For example, if you create a private field, that field can’t be accessed outside the class. That private field can only be used internally in that class.


Internal

If you set internal as an access specifier, this means that the entity is only accessible within the same assembly. All the classes in the assembly can access this class or member. When you build a project in .NET, it creates an assembly file, either dll or exe. There could be many assemblies in one solution, and internal members are only accessible by the classes on those particular assemblies.


Protected

Protected members are accessible by the class itself, as well as the child classes that inherit the class. Other than that, no other class can access a protected member. The protected access modifier is very useful when inheritance takes place.


Protected Internal

A protected internal is a combination of a protected access modifier and an internal access modifier. A member whose access modifier is protected internal can be accessed by all classes in the same assembly, as well as by any class that inherits it, regardless of the assembly. For example, say that you have a class named Animal in an assembly called Assembly1.dll. In the Animal class, there is a protected internal method called GetName. Any other class in Assembly1.dll can access the GetName method. Now, suppose there is another assembly named Assembly2.dll. In Assembly2.dll, there is a class named Dog that extends the Animal class. As GetName is a protected internal, even though the Dog class is in a separate assembly, it can still access the GetName method.

Raihan Taher


OOP is one of the most important programming methodologies nowadays. The whole concept depends on four main ideas, which are known as the pillars of OOP. These four pillars are as follows:

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

Abstraction: If something is abstract, it means that it doesn’t have an instance in reality but does exist as an idea or concept. In programming, we use this technique to organize our thoughts. This is one of the pillars of OOP. In C#, we have abstract classes, which implement the concept of abstraction. Abstract classes are classes that don’t have any instances, classes that implement the abstract class will implement the properties and methods of that abstract class.


Encapsulation: Encapsulation means hiding or covering. In C#, encapsulation is achieved by access modifiers. The access modifiers that are available in C# are the following:

  • Public
  • Private
  • Protected
  • Internal
  • Internal protected

Encapsulation is when you want to control other classes’ access to a certain class. For security reasons, it isn’t a good idea to make that class accessible to all classes. You can also limit access to the properties and variables of a class. Like variables and properties, you can also use access specifiers for methods. Encapsulation is a very important part of OOP as it gives us control over code


Inheritance: The word inheritance means receiving or deriving something from something else. In real life, we might talk about a child inheriting a house from his or her parents. In that case, the child has the same power over the house that his parents had. This concept of inheritance is one of the pillars of OOP. In programming, when one class is derived from another class, this is called inheritance. This means that the derived class will have the same properties as the parent class. In programming terminology, the class from which another class is derived is called the parent class, while the classes that inherit from these are called child classes.


Polymorphism: The word polymorph means many forms. To understand the concept of polymorphism properly, let’s work with an example. Let’s think about a person, such as Bill Gates. We all know that Bill Gates is a great software developer, business man, philanthropist, and also a great human being. He is one individual, but he has different roles and performs different tasks. This is polymorphism. When Bill Gates was developing software, he was playing the role of a software developer. He was thinking about the code he was writing. Later, when he became the CEO of Microsoft, he started managing people and thinking about growing the business. He’s the same person, but with different roles and different responsibilities.

In C#, there are two kind of polymorphism: static polymorphism and dynamic polymorphism. Static polymorphism is a kind of polymorphism where the role of a method is determined at compilation time, whereas, in dynamic polymorphism, the role of a method is determined at runtime. Examples of static polymorphism include method overloading and operator overloading. Writing a method with the same name as another method, but with different parameters, is called method overloading. This is a kind of polymorphism. Like method overloading, operator overloading is also a static polymorphism.

Dynamic polymorphism refers to the use of the abstract class. When you write an abstract class, no instance can be created from that abstract class. When any other class uses or implements that abstract class, the class also has to implement the abstract methods of that abstract class. As different classes can implement the abstract class and can have different implementations of abstract methods, polymorphic behavior is achieved. In this case, we have methods with the same name but different implementations.


In the next code, show an example of abstraction, encapsulation, inheritance and polymorphism.

Raihan Taher


C# is a fully Object oriented programming language “OOP”, the first word is object, an object is something that can be seen, felt, or touched; something that has physical existence in the real world, if an item is virtual, this means that it doesn’t have any physical existence and is not considered an object. The second word is oriented, which indicates a direction or something to aim for, for example, when we say that we are oriented toward the building, we mean that we are facing towards it.
The third word is programming. Programming is just giving instructions to the computer. As the computer doesn’t speak our language, we humans have to give instructions to the computer in a language that the computer understands. We humans call these instructions computer programs, as we are guiding or instructing a computer to do a particular thing.

OOP means that we write our computer programs by keeping objects at the center of our thinking. OOP is neither a tool nor a programming language it is just a concept. Some programming languages are designed to follow this concept. C# is one of the most popular OOP languages. There are other object oriented languages, such as Java, C++, and so on.
In OOP, we try to think about our software components as small objects, and create relationships between them to solve a problem.

In OOP, you derive objects from classes. Classes are one of the most important concepts in OOP, you can say they are the building blocks of OOP. A class can be described as the blueprint of an object. A class is like a template or blueprint that tells us what properties and behaviors an instance of this class will have. In most circumstances, a class itself can’t actually do anything, it is just used to create objects.

An object is an instance of a class. In other words, an object is an implementation of a class. For example, in a banking application, we have a Customer class, but that doesn’t mean that we actually have a customer in our application. To create a customer, we have to create an object of the Customer class.

A variable is something that varies, which means it is not constant. In programming, when we create a variable, the computer actually allocates a space in memory for it so that a value of the variable can be stored there.

A method is a piece of code that is written in the code file and can be reused. A method can hold many lines of code, which will be executed when it is called. Let’s take a look at the general form of a method:

access_modifier return_type name(parameter_list)
{
   //Method body
}

The first thing in the method declaration is an access_modifier, this will set the access permission of the method. Then, we have the return_type of the method, which will hold the type that the method will return, such as string, int, double, or another type. After that, we have the method name and then brackets, which indicate that it is a method. In the brackets, we have the parameter list, this can either be empty or can contain one or more parameters. Finally, we have curly brackets, which hold the method body, the code that the method will execute goes inside here. Any code following this structure will be considered a method by the C# compiler.

In every class, there is a special type of method, called a constructor. You can create a constructor in a class and program it, if you don’t create one yourself, the compiler will create a very simple constructor and use that instead. A constructor is a method that gets triggered when an object of a class is created. A constructor is mainly used to set the prerequisites of the class. A constructor doesn’t have a return type. This is because a constructor can’t return anything; it’s for initialization, not for any other type of action. Normally, the type of access is public for constructors, because otherwise no object can be instantiated. If you specifically want to prevent objects of a class from being instantiated, you can set the constructor as private. Another interesting thing is that you can have multiple constructors in a class. You might have one constructor that takes one argument and another that doesn’t take any arguments. Depending on the way in which you are initializing the object, the respective constructor will be called.

access_modifier class_name(parameter_list)
{
   //Constructor body
}

In the next example, show the use of classes, objects, variables and constructors.

Raihan Taher


Overview of C# as a Language

With the introduction of modern day programming practices, it is evident that developers are looking for more advanced constructs to help them to deliver the best software in the most effective way. Languages that evolve on top of frameworks are built to enhance the capabilities of the developers in a way that allows them to quickly build their code with less complexity so that the code is maintainable, yet readable.

There are many high level object oriented programming languages available on the market, C# is not new in the programming world and has existed for over a decade, but with the dynamic progress of the language itself creating so many newe constructs, it has already oriented, type safe, general purpose language that is built on top of the .NET framework that was developed by Microsoft and approved by the European Computer Manufacturers Association (ECMA) and the International Standarts Organization (ISO). It is built to run on the Common Language Infrastructure and can interact with any other languages that are built based on the same architecture. Inspired by C++, the language is rich in delivering the best of breed applications without handling too many complexities in code.

Evolution Of C#

C# has been one of the most dynamic languages in recent times, this language is open source, some of the major enhancements that have been put forward for the language include Generics, LINQ, Dynamics, and the async/await pattern. In the next image, we can see how the language has evolved.

Various stages of C#

Managed Code: The phrase came into beign after Microsoft declared the .NET framework, any code running in a managed environment is handled by Common Language Runtime (CLR).

Generics: Is a concept that was introduced with C# 2.0 and allow template type definition and type parameters, Generics allow the programmer to define types with opened-ended type parameters that dramatically changed the way that the programmers write code. The type-safety with dynamic typed generic templates improves readability, reusability, and code performance.

LINQ: Language Integrated Query, is a new construct of queries that can be run over structures. LINQ is very new to the programming world and gives us a glimpse of functional programming on top of object oriented general programming structure. LINQ also introduced a bunch of new interfaces in the form of the IQueryable interface, which introduced a number of libraries that can interact with the external world using LINQ. LINQ was boosted with the introduction of Lambda expressions and expression trees.

Dynamics: The dynamic programming capability helps the developer to defer the programming calls to runtime. There is a specific syntactic sugar that was introduced in the language that compiles the dynamic code on the same runtime. The version also puts forward a number of new interfaces and classes that enhace its language capabilities.

Async/await: With any language, threading or asynchronous programming is a pain. When dealing with asynchrony, the programmers have to come across many complexities that reduce the readability and maintainability of the code, with the async/await feature, programming in a asynchronous way is as simple as synchronous programming. The programming has been simplified, with all of the complexities handled by the compiler and the framework internally.

Compiler as a service: Microsoft has been working on how some parts of the source code of the compiler can be opened up to the world. Consequently, as a programmer, you are capable of querying the compiler on some of its internal work principles. C# 6.0 introduced a number of libraries that enable the developer to get an insight into the compiler, the binder, the syntax tree of the program, and so on.

Exception filters: Exception filters are newly introduced and give a program the capability to filter out certain exception types. The exception filters, being a CLR construct, have been hidden in the language throughout its lifetime, but were finally introduced with C# 6.0.

C# 8 and beyond: With C# being the most dynamic language in the market, it is constantly improving. With the newer features, such as nullable reference types, async streams, ranges and indices, interface members, and many other features that came with the latest version of C#, they have enhanced the basic features and helped programmers to take advantage of these new constructs, hence making their lives easier.

Architecture of .NET

.NET framework is still well built and makes sure to make it tiered, moduler, and hierarchical. Each tier provides specific functionalities to the user some in terms of security and some in terms of language capabilities. The tiers produce a layer of abstraction to the end users and hide most of the complexities of the native operating system as much as possible. The .NET framework is partitioned into modules, with each of them having their own distinct responsibilities. The higher tiers request specific capabilities from the lower tiers and hence it is hierarchical. In the next image shows a diagram of the .NET architecture.

 .NET architecture
.NET architecture

On its lowest level, it is the operating system that interacts with the kernel APIs that are present in the operating system. The Common Language Infrastructure connects with the Common Language Runtime, which provides services that monitor each code execution and managed memory, handles exceptions, and ensures that the application behaves as intended. Another important goal of the infrastructure is language inter-operability. The common language runtime is yet again abstracted with the .NET class libraries. This layer holds the binaries that the language is built on, and all of the compilers built on top of the libraries provide the same compiled code so that the CLR can understand the code and interact easily with one another.

Common Language Runtime: The CLR provides an interfacing between the underlying unmanaged infrastructure with the managed environment. This provides all of the basic functionalities of the managed environment in the form of garbage collection, security, and interoperability. The CLR is formed with the just-in-time compiler, which compiles the assembly code that’s produced with the specific compilers to the native calls. CLR is the most important portion of the .NET architecture.

Common Type System: Is a layer of abstraction between the language and the framework, it is evident that each of the language literals are mapped to specific CLR types. It is always preferred to use language types since the compiler takes care of the mapping of types. The CTS system is built as a hierarchy of types with System.Object at its apex. The Common Type System (CTS) is divided into two kinds, one of which is value types, which are primitives that are derived from System.ValueTypes, while anything other than that is a reference type. The value types are treated differently to the reference types. This is because while allocation of memory value types are created on a thread stack during execution, reference types are always created on the heap.

.NET framework class libraries: The framework class library lies in-between the language and the CLR, and therefore any type that’s present in the framework is exposed to the language you code. The .NET framework is formed with a good number of classes and structures, exposing never-ending functionalities that you, as a programmer, can benefit from. The class libraries are stored in the form of binaries that can be referenced directly from your program code.

Just in time compiler: .NET languages are compiled twice. During the first form of compilation, the high level language is converted into a Microsoft Intermediate Language (MSIL), which can be understood by the CLR, while the MSIL is again compiled during runtime when the program is executed. The JIT works inside the program runtime and periodically compiles the code that is expected to be required during execution.