1

I'm developing a .NETcore project where i use the apicontrollers to handle front-end requests and i'm manually parsing the JObject like so:

    public IActionResult CreatePublicUser([FromBody]JObject body)
    {

        string Username = body["Username"].ToString();
    }

I have Created an enum that basically allows me to use enumUser.Username.toString() instead of writing "Username" explicitly

    public enum enumUserModel
    {
        Username,
        Password
    }

however apparently i have to do this way too often so i decided to create a class with constants like so:

public class UserModelConstants {

     public static const Username = "Username";
     public static const Password = "Password";
}

so i can instead write UserModelConstants.Username which makes the code looks better and easier to understand. Moreover, according to online articles it has better performance than enumUser.Username.toString()

but if i use the constants approach then i'll have to write another class to handle converting the constants to int for writing to database (which is basically using enum again).

so what the best way to approach this?

Hammadi
  • 51
  • 5
  • 1
    `enumUserModel.Username.ToString()`. If you've determined by real metrics that runtime efficiency is an issue, `public static const Username = enumUserModel.Username.ToString();` Avoid "magic strings" if you can. – 15ee8f99-57ff-4f92-890c-b56153 Jun 03 '19 at 19:16
  • 1
    @EdPlunkett You can't assign `ToString()` to a `const`, can you? – GSerg Jun 03 '19 at 19:25
  • 1
    Another approach: https://stackoverflow.com/q/2650080/11683 – GSerg Jun 03 '19 at 19:27
  • 2
    @GSerg Whoops! Good point. I should have said `public static readonly String Username = enumUserModel.Username.ToString();` I'm a big fan of Description attributes on enums, too. I'd urge OP to consider that approach. It's a static method, so it can be used to initialize a readonly static field. – 15ee8f99-57ff-4f92-890c-b56153 Jun 03 '19 at 19:27
  • @Ed-Plunkett Nice idea i will try it thanks! – Hammadi Jun 03 '19 at 20:03

0 Answers0