D
D
Dima Sokolov2019-10-03 10:26:02
C++ / C#
Dima Sokolov, 2019-10-03 10:26:02

C# method returning generic type and type conversion?

Method:

class Cat { }

        public List<T> method<T>()
        {
            return new List<Cat>(); // вместо new тут List<Любой тип>  который приходит из EntityFramework
        }

Method call:
var c = method<Cat>();
And the error is that you cannot implicitly convert the type from List<Type> to List The
question is why does this not work, if we can return a List then why can't we return a List<Type> ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Developer, 2019-10-03
@dimka11

The method declaration must have the same type that is returned from within:

public class Cat<T>{
        public List<T> method()
        {
            return new List<T>();
        }
    }

    public class Kitty
    {
        public void main()
        {
            Cat<String> kitty = new Cat<String>();
            List<String> kittyMethods = kitty.method();
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question