C# language: Generics types

I will say a little today about generics types, they are similar to the lists but are a bit different in that the lists are already generics types ready today, we will look into the tripe lists and see how they work from the inside.

The lists are ready classes in .NET, knowing the generics types, you can create your own class similar to lists and use it eg the queue in the lists was created like this (add a namespace at the top):

From the inside the queue looks like this and the generics types are used there:

Now delete only the namespace without removing the first script added at the top and see the effect. In both solutions, the effect is the same, right?

How it’s working? I already explaing in the script in which we have created our own queue class, there is nothing new except this “T”.

In the “Main” function, we created the Queue object and the type that should be used in this queue, ie int, so int in the Queue class we insert in place of the “T” parameter, after creating the int type in the queue in the “Main” function, the Queue class looks like this:

What for are the generics types?

Generics types are used to write code with different types of data or data whose types you will not know eg if you were making a game and having a character with various statistics such as hero’s name, amount of strength, dexterity etc. and you would not be able to define types, then you could in this use generics types.

Generics methods

We will do now, for example, the generics method.

The most important thing to know in this example is that the method will generate the appropriate type based on the types of arguments passed.

Inheritance after generic classes

Implementing generics interfaces in classes

“default” key word

In generic types there is a default key word, it just resets the variable, the default value for int is zero.

The following example will display zero in the console.

This content also you can find on my steemit blog: https://steemit.com/programming/@slawas/c-language-generics-types

And on medium: https://medium.com/@sawomirkowalski/c-language-generics-types-220d5b97805b

 
If that post was useful for you share it with your friends :)

Post a comment

Be first!

avatar
  Subscribe  
Notify about