K
K
Ksenia2019-02-23 20:46:05
C++ / C#
Ksenia, 2019-02-23 20:46:05

How to deal with generic types?

I read an article about delegates. Everything seems to be clear, but there were generalized types that I didn’t fully understand. At an intuitive level, the connections in the code are clear, but ...

delegate T Operation<T, K>(K val);
 
class Program
{
    static void Main(string[] args)
    {
        Operation<decimal, int> op = Square;
 
        Console.WriteLine(op(5));
        Console.Read();
    }
 
    static decimal Square(int n)
    {
        return n * n;
    }
}

If you specifically say the line:
delegate T Operation<T, K>(K val);
then you get something like: "We declare a delegate with a return value of type T, which is called Operation, and the delegate's parameters are a val value of type K". Correctly? Where to fasten Operation in this phrase. What is <T, K>? Well, it is clear that it indicates what types are used in the Operate delegate, but what is it called? Explain in Russian, please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Esin, 2019-02-23
@Exomode

Generics are when you expect certain types to be used in a context and you need to bind them according to certain criteria. It also saves you the hassle of having to type cast later in your code.
As an example, task: You need to implement class A with property F, which can be any type implemented from interface IB:
Solution 1. Non-optimized approach without generics:

class A {
  IB F { get; }
}

A a = new A();
C c = a.F as C; // Здесь придется приводить к типу.

Solution 2: Generic option:
class A<T> {
  T F { get; }
}

A<C> a = new A<C>();
C c = a.F; // Здесь лежит сразу экземпляр типа C, приводить к типу не нужно.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question