Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a value of a model dynamically

Tags:

c#

.net

I have a method, which calls the API and returns a model as shown below:

public class Book
{
   string Name { get; set; }
   string Author { get; set; }
   string Genre { get; set; }
}

This is an example function,

public static string GetValue(object reference)
{
    Book book = new Book();
    book.Name = "A";
    book.Author = "B";
    book.Genre = "C";

    return ?? // I have no idea
}

If I call GetValue(Name) then the method should return book.Name value. If I call GetValue(Genre) then the method should return book.Genre.

How can I do it?

like image 731
Ranjith Varatharajan Avatar asked Dec 05 '25 22:12

Ranjith Varatharajan


1 Answers

While this seems a strange use-case, you generally want to return the book, and then directly access the properties on the book. If you need a property multiple times now, your method will call the API every time you try to access one property with this method.

So the direct approach would probably be something like this:

   public static R GetValue<R>(Func<Book, R> selector) {
        Book book = new Book();
        book.Name = "A";
        book.Author = "B";
        book.Genre = "C";

        return selector(book);
    }

You can then get the value of this book by using a lambda function to indicate what you want:

var name = GetValue(b => b.Name);

You could then generalize this, to be ably to return any value when you provide it as an input, by making it an extension method:

public static R GetValue<T, R>(this T value, Func<T, R> selector) {
    return selector(value);
}

then create a new book, and getting the value like this:

var name = book.GetValue(b => b.Name);

However, you are now in the place where this is a much more direct way to do this:

var name = book.Name;

At this point, we're back at my initial suggestion, just get the entire book from wherever you're getting it, and directly access the properties on it.

like image 194
ThoNohT Avatar answered Dec 08 '25 10:12

ThoNohT