How To Create A Custom Attribute And Get The Value

I was performing a code and one of the developers needed to return a success/failure result from a method and in the event of an error, return an error message. To solve the problem he used an out parameter like this:

public bool IsSuccess(string value, out message)
{
if(!string.IsNullOrEmpty(value)
return true;
message = "Message is empty";
return false;
}

The above snippet is a very simple version of the example in question but this is a big code smell for me. Personally, I hate out parameters and for me it’s a sign that the method is trying to do too much. My preferred way to fix this would be to return a custom enum and then use a custom attribute on the enum to define the error messages. In code we could then use an extension method on the enum to return us the error message. Using this approach means we can get rid of the out parameter and we don’t have all the error message tangled all over our solution.

To create a custom attribute for the enum we need to inherit from the attribute class.

public class ErrorMessageAttribute : Attribute
{
public string Name { get; set; }
}

On the enum itself we would then add the [ErrorMessage] attribute we just created and add the error message:

public enum SystemState
{
Success = 0,
[ErrorMessage("The system can not load")]
SystemFailure = 1,
[ErrorMessage("TThe input value needs a value")]
ParameterNotIntialise = 1,
}

Out code can now be factored to be a lot more cleaner like this:

public SystemState IsSuccess(string value)
{
return string.IsNullOrEmpty(value) ? SystemState.ParameterNotIntialise : SystemState.Success ;
}

I’m sure we agree this code is a lot more simpler and easier to read.  To get access to the error message we can then use this extension:

public static string GetSuccessState (this SystemState  value)
{
return value.GetAttributeOfEnumValue<ErrorMessageAttribute >().Select(x => x.Name);
}

Finally, in our code we can just do

var value = IsSuccess(string value)
value.GetSuccessState();

Using this approach we can get rid of that nasty if statement we can add errors and extra states using the open/closed principle.

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *