c# - Force developer to use string from special class -


i have objectresult return error message if error occurs. i’d developer not able type own message this; should have use 1 of set of predetermined message string in special class (just manage message).

for example, don’t want possible:

objectresult obj = new objectresult() {message = "xxx"}; 

a developer should have write:

objectresult obj = new objectresult() {message = messagesstore.somemessage}; 

how can implement this?

declare enum , decorate entries description attributes

public enum messagesstore {      [description("everything ok")]     ok,     [description("everything not ok")]     notok } 

use following extension method

 public static class enumextensions {     public static string getenumdescription(this enum value)     {         var fi = value.gettype().getfield(value.tostring());          var attributes =             (descriptionattribute[])fi.getcustomattributes(             typeof(descriptionattribute),             false);          if (attributes != null &&             attributes.length > 0)         {             return attributes[0].description;         }          return value.tostring();     } } 

and, example of usage:

var ms = messagesstore.ok; var desc = ms.getenumdescription(); 

desc "everything ok"


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -