TiagoDias
TiagoDias

Reputation: 1865

Enumeration best practices

I'm defining a couple of classes to represent transactions and i need to define a TransactionType enum.

A prototype for my class is:

public class Transaction
{
    public enum Type { Income, Outcome }

    public DateTime Date { get; set;}
    public Type Type { get; set;}
    public decimal Amount { get; set;}
}

Some people would say that TransactionType enum should be declared on namespace scope, but for those i'would say that this Type is only related to the Transaction so IMO it should be declared inside the class. If i declare it in the class, there's a compiler error in field Type declaration. Should i name it Types? Guess not too because i need to refer Income as a Type and not as Types.

Please say what you think about this topic, thanks.

Upvotes: 0

Views: 226

Answers (4)

Christian Hayter
Christian Hayter

Reputation: 31071

Call the enum TransactionType and move it outside the class. That name is just as descriptive as Transaction.Type, and it solves the naming conflict problem.

Upvotes: 1

oleksii
oleksii

Reputation: 35905

You would try to define any type with the smallest visibility possible. In your case public enum Type { Income, Outcome } is public so it doesn't really matter. If it was private then you would keep it as a nested type.

Best practices would be to keep all public types in separate files.

Upvotes: 0

HCL
HCL

Reputation: 36775

Type is one of the most important classes of System.Reflection. I would use another name because it is very ambigious.

Upvotes: 2

Sergii Kudriavtsev
Sergii Kudriavtsev

Reputation: 10512

Make it TransactionType then. It will be still short enough yet it will make your code much more readable.

Upvotes: 0

Related Questions