DEV Community

artydev
artydev

Posted on

What occurs when coding in C# from Javascript perspective...

When you embrace a programming language you have to use it's specific idioms.

But this time I and want to see what can be accomplish when coding in C# thinking in Javascript...

Let's create a tool which interrogates a Web API

Here is the structure of the application :

Folders

TodoRecord.cs

namespace RequestApp.Todos
{
    public record class Todo(
        int? Userid = null,
        int? Id = null,
        string? Title = null,
        bool? Completed = null
    );
}
Enter fullscreen mode Exit fullscreen mode

TodoRequester.cs


using RequestApp.Todos;
using System.Net.Http.Json;

namespace RequestApp
{
    public static class TodoRequester
    {
        const string urlTodo = "https://jsonplaceholder.typicode.com";

        public static Func<Task<List<Todo>>> Request()
        {
            HttpClient client = new() { BaseAddress = new Uri(urlTodo) };

            return async () =>
            {
                var request = await client.GetFromJsonAsync<List<Todo>>("/todos");

                return request ?? new List<Todo>();
            };
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

Program.cs

namespace RequestApp
{
    static class Program
    {
        private static async Task Main(string[] args)
        {
            var first = await TodoRequester.Request()();

            Console.WriteLine(first.First());

            Console.WriteLine("-------------------");

        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Result :

Result

I would certainly not use this type of code in my team, but for my personnal projects that fits my needs....

Top comments (0)