G
G
getfield2021-08-12 12:21:57
.NET
getfield, 2021-08-12 12:21:57

C#. Is it possible to create a method in which the return type will be determined in the method itself?

Is it possible to create a method in which the return type will be determined in the method itself, or dotnet strict typing will not allow this?
The returned type will depend on what comes in the response from the API (several type options that will be explicitly specified in the method itself).

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
Vasily Bannikov, 2021-08-12
@vabka

The returned type will depend on what comes in the response from the API (several type options that will be explicitly specified in the method itself).

Just make a class that has some kind of flag that tells the content type and N properties for each type.
If you have only two types - result and error, then use Either
https://habr.com/en/post/267231/

F
freeExec, 2021-08-12
@freeExec

You return the most basic type object, but this is shit code. The API usually returns a known data structure.

G
Griboks, 2021-08-12
@Griboks

No, C# does not support type unioning. You can generalize, use a template or container, inherit, use an interface. But the most correct solution would be to rewrite the api method so that it returns a previously known type (this is the point of api).

H
HemulGM, 2021-08-13
@HemulGM

You need generics " <T>"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question