Difference between Display and Description attribute - c#

I'm trying to enhance my enum so I've tried a suggestion on Display and another one on Description.
I'm annoyed because I don't understand the difference between them. Both Description class and Display class are from framework 4.5.
It's additionally annoying since neither of them work in the code. I'm testing the following but I only get to see the donkeys...
[Flags]
public enum Donkeys
{
[Display(Name = "Monkey 1")]
Donkey1 = 0,
[Description("Monkey 2")]
Donkey2 = 1
}

Neither of these attributes have any effect on the enum's ToString() method, which is what gets called if you just try to insert it into a Razor template. ToString() always uses the name declared in code -- Donkey1 and Donkey2 in your case. To my knowledge, there's no built-in way to specify an alternate string representation for the enum to use automatically.
I assume there are (at least) two reasons for that:
Serialization. ToString() uses the name so that Enum.Parse() can parse it back into the enum.
Localization. .NET was designed with global audiences firmly in mind, and if you want a human-readable string representation of an enum, it's extremely unlikely that there will be just one string representation, at which point it's going to be up to your application to figure out how to do it.
If you know your app will never be translated to other languages, or if you just want a string representation you can use in debug output, you're welcome to use an attribute (either one from the Framework, or one you declare yourself) to define a string representation for each enum value, and write some utility functions to do the string conversion. But you can't make the enum's ToString() do it for you (since that would break serialization); you'd have to write your own code to do it.
However, since you're writing a Web app, there's a fair chance that you will have a global audience -- in which case you'll need to localize your enum strings the same way you localize all your other text.

Related

I'm looking for a way to create new "primitive" types with additional constraints which are visible at coding time to users of the type

Suppose I have an entity in my universe of discourse called a Widget.
Suppose the Widget has an attribute called a WidgetCode. This attribute is defined (by the system of record) to be an alphanumeric value (ie, it's a string) of length exactly 8.
I might implement that in code as follows:
class Widget
{
private string _WidgetCode;
public string WidgetCode
{
get => _WidgetCode;
set
{
if (value.Length != 8) { throw new Exception("length must be 8"); }
_WidgetCode = value;
}
}
}
This is OK, but not ideal. The test in the setter will prevent the property from accepting an invalid value at runtime. But if some other developer wants to make use of my class, then the only way they can find out that the constraint exists is by looking at the implementation of the setter. Which would, of course, violate some pretty fundamental computer science 101 concepts.
In contrast we can look into the world of relational databases. In that world there is a fundamental type. "character", but I can create what is essentially a completely different type when I actually make use of it by specifying the length as part of the type. In the case of a WidgetCode, that would be a char(8). I can add other restrictions as well, in the form of check constraints.
When I do this, I have effectively created a new, more "refined" primitive type, which represents a WidgetCode, and does not represent any arbitrary string value of any arbitrary length.
More importantly, any SQL developer who needs to interact with my schema can see the constraints on my new type. They don't have to go and read separate documentation stored outside the schema. They don't have to live in ignorance of the constraint and hope that they never run afoul of some hidden constraint that they can't see while writing code. The constraint is declared in the schema, and the same thing which implements the constraint also documents it. It is impossible for the "documentation" to get out of synch with the implementation.
This idea doesn't have to be limited to strings. We might want to store a property called Percentage, and declare its domain as a real number between 0 and 1 with scale 3, such that it should not be possible to write the value 1.5 to this property. Once again in a relational schema, that could be a Percentage decimal(4,3) not null check (Percentage between 0 and 1).
Is there any mechanism in C# whereby that same kind of more refined type can be created, and where developers using that type can see the constraint at coding-time without having to go and read some external documentation, hoping that the documentation is up to date?
DataAnnotations get some of the way there, but they are clearly designed to inform users (specifically of GUIs) about a problem with an entered value at runtime. I am looking for a similar kind of tagging which provides the same information to developers making use of the type at coding time.
This question has been answered to my satisfaction through a combination of the comments by Eric Lippert and Matthew.
There is no particular built in language support, nor any particular annotation package, but one possibly functional approach may be to use T4 text templates.

When does the ProtoEnum attribute need to be used for protobuf-net?

The protobuf-net includes a [ProtoEnum] attribute that can be used to decorate members of an enum. When and how should this be used?
In normal usage scenarios, enum member serialization seems to work just fine (as long as the enum itself has a [ProtoContract] decorating it).
The only times you need this are:
when you're working .proto => C# or C# => .proto, and you want the name in the .proto to be different to the actual enum declaration
when you want to map the numbers on the wire to numbers in your type model for some reason, i.e. the enum value that is 12 on the wire (to other users of the same data) would more usefully be 20 to your app somehow
I usually strongly discourage the second option; it makes things too complex, and it means it needs to apply an extra bit of logic in both directions. This is especially true now that "proto3" changed the expected behavior of unrecognized values; in "proto2", this was meant to indicate an error, but in "proto3" you're meant to just take the value. You can't do this if you're applying a map.

Building a string representation of an object using a "mask" or user supplied Format String

I'm not really sure what tags should be on this sort of question so feel free to give me some suggestions if you think some others are more suited.
I have a dynamic object with an unknown number or properties on it, it's from a sort of dynamic self describing data model that lets the user build the data model at runtime. However because all of the fields holding relevant information to the user are in dynamic properties, it's difficult to determine what should be the human readable identifier, so it's left up to the administrator. (Don't think it matters but this is an ASP.NET MVC3 Application). To help during debugging I had started decorating some classes with DebuggerDisplayAttribute to make it easier to debug. This allow me to do things like
[DebuggerDisplay(#"\{Description = {Description}}")]
public class Group
to get a better picture of what a specific instance of an object is. And this sort of setup would be perfect but I can't seem to find the implementation of this flexibility. This is especially useful on my dynamic objects because the string value of the DebuggerDisplayAttribute is resolved by the .NET framework and I have implementations of TryGetMember on my base object class to handle the dynamic aspect. But this only makes it easier for development. So I've added a field on what part of my object is still strongly typed and called it Title, and I'd like to let the administer set the implementation using their own format, so to speak. So for example they might build out a very simplistic rental tracking system to show rentals and they might specify a format string along the lines of
"{MovieTitle} (Due: {DueDate})"
I would like that when they save the record to add some logic to first update the Title property by resolving the format string to substitute each place holder with the value of the appropriate property on the dynamic object. So this might resolve to a title of
"Inception (Due: May 21, 2011)", or a more realistic scenario of a format string of
"{LastName}, {FirstName}"
I don't want the user to have to update the title of a record when they change the first name field or the last name field. I fully realize this will likely use reflection but I'm hoping some one out there can give me some pointers or even a working example to handle complex format strings that could be a mix if literal text and placeholders.
I've not had much luck looking for an implementation on the net that will do what I want since I'm not really sure what keywords would give me the most relevant search results?
You need two things:
1) A syntax for formatting strings
You have already described a syntax where variables are surrounded by bracers, and if you want to use that you need to build a parser that can parse that. Perhaps you also want to add ways to specify say a date or a number format.
2) Rules for resolving variables
If there is a single context object you can use reflection and match variable names to properties but if your object model is more complex you can add conventions for searching say a hierarchy of objects.
If you are planning to base your model objects on dynamic chances are that you will find the Clay library on CodePlex interesting.

How can I internationalize strings representing C# enum values?

I've seen many questions and answers about mapping strings to enums and vice-versa, but how can I map a series of localized strings to enums?
Should I just create an extension method like this that returns the proper string from a resource file? Is there a way to localize attributes (like "Description") that are used in solutions like this?
Which is the preferred solution - extension method or attributes. It seems to me that this isn't the intended purpose of attributes. In fact, now that I think about it, if I were to use an extension method an attribute seems like something I'd use to specify a key in a resource file for the localized string I want to use in place of the enum value.
EDIT - example:
Given the following enum,
public enum TransactionTypes {
Cheque = 1,
BankTransfer = 2,
CreditCard = 3
}
I would like a way to map each type to a localized string. I started off with an extension method for the enum that uses a switch statement and strongly typed references to the resource file.
However, an extension method for every enum doesn't seem like a great solution. I've started following this to create a custom attribute for each enumerated value. The attribute has a base name and key for the resource file containing localized strings. In the above enum, for example, I have this:
...
[EnumResourceAttribute("FinancialTransaction", "Cheque")]
Cheque = 1,
...
Where "FinanacialTransaction" is the resx file and "Cheque" is the string key. I'm trying to create a utility method to which I could pass any value from any enumeration and have it return the localized string representation of that value, assuming the custom attribute is specified. I just can't figure out how to dynamically access a resource file and a key within it.
I would definitely suggest using a resource file, probably with a method (extension or otherwise) to make it simple to get hold of the relevant resource. As the number of languages you support grows, you don't really want the code to be full of text, distracting you from the values themselves.
Likewise translation companies are likely to be geared up to handle resx files - they're not going to want to mess around in your source code, and you shouldn't let them do so anyway :)
Just use resources which are keyed on the name of the enum and the value within it. Straightforward, scales to multiple enums and multiple languages, doesn't clutter up your source code, works well with translation tools, and is basically going along with the flow of i18n within .NET.
EDIT: For mapping the enum values to the resource names, I'd just do something like:
public static string ToResourceName<T>(this T value) where T : struct
{
return typeof(T).Name + "." + value;
}
Then you could do:
string resource = MyEnum.SomeValue.ToResourceName();
Obviously that's performing string concatenation every time - you could cache that if you wanted to, but I wouldn't bother unless you had some indication that it was actually a problem.
That doesn't stop you using the extension method for non-enums, of course. If you want to do that, you need something like Unconstrained Melody.
I continued with the custom attributes and created this utility method:
public static string getEnumResourceString(Enum value)
{
System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());
EnumResourceAttribute attr = (EnumResourceAttribute)System.Attribute.GetCustomAttribute(fi, typeof(EnumResourceAttribute));
return (string)HttpContext.GetGlobalResourceObject(attr.BaseName, attr.Key);
}

Properties vs Methods

Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?
We are busy having this debate and have found some areas where it is debatable whether we should use a property or a method. One example is this:
public void SetLabel(string text)
{
Label.Text = text;
}
In the example, Label is a control on a ASPX page. Is there a principle that can govern the decision (in this case) whether to make this a method or a property.
I'll accept the answer that is most general and comprehensive, but that also touches on the example that I have given.
From the Choosing Between Properties and Methods section of Design Guidelines for Developing Class Libraries:
In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.
Yes, if all you're doing is getting and setting, use a property.
If you're doing something complex that may affect several data members, a method is more appropriate. Or if your getter takes parameters or your setter takes more than a value parameter.
In the middle is a grey area where the line can be a little blurred. There is no hard and fast rule and different people will sometimes disagree whether something should be a property or a method. The important thing is just to be (relatively) consistent with how you do it (or how your team does it).
They are largely interchangeable but a property signals to the user that the implementation is relatively "simple". Oh and the syntax is a little cleaner.
Generally speaking, my philosophy is that if you start writing a method name that begins with get or set and takes zero or one parameter (respectively) then it's a prime candidate for a property.
Searching through MSDN, I found a reference on Properties vs Methods that provides some great guidelines for creating methods:
The operation is a conversion, such as Object.ToString.
The operation is expensive enough that you want to communicate to the
user that they should consider caching
the result.
Obtaining a property value using the get accessor would have an observable
side effect.
Calling the member twice in succession produces different results.
The order of execution is important. Note that a type's properties should
be able to be set and retrieved in any
order.
The member is static but returns a value that can be changed.
The member returns an array. Properties that return arrays can be
very misleading. Usually it is
necessary to return a copy of the
internal array so that the user cannot
change internal state. This, coupled
with the fact that a user can easily
assume it is an indexed property,
leads to inefficient code.
If you're setting an actual property of your object then you use a property.
If you're performing a task / functionality then you use a method.
In your example, it is a definite property being set.
If however, your functionality was to AppendToLabel then you would use a method.
Properties are a way to inject or retrieve data from an object. They create an abstraction over variables or data within a class. They are analogous to getters and setters in Java.
Methods encapsulate an operation.
In general I use properties to expose single bits of data, or small calculations on a class, like sales tax. Which is derived from the number of items and their cost in a shopping cart.
I use methods when I create an operation, like retrieving data from the database. Any operation that has moving parts, is a candidate for a method.
In your code example I would wrap it in a property if I need to access it outside it's containing class:
public Label Title
{
get{ return titleLabel;}
set{ titleLabel = value;}
}
Setting the text:
Title.Text = "Properties vs Methods";
If I was only setting the Text property of the Label this is how I would do it:
public string Title
{
get{ return titleLabel.Text;}
set{ titleLabel.Text = value;}
}
Setting the text:
Title = "Properties vs Methods";
Symantically properties are attributes of your objects.
Methods are behaviors of your object.
Label is an attribute and it makes more sense to make it a property.
In terms of Object Oriented Programming you should have a clear understanding of what is part of behavior and what is merely an attribute.
Car { Color, Model, Brand }
A car has Color, Model and Brand attributes therefore it does not make sense to have a method SetColor or SetModel because symantically we do not ask Car to set its own color.
So if you map the property/method case to the real life object or look at it from symantic view point, your confusion will really go away.
You need only look at the very name... "Property". What does it mean? The dictionary defines it in many ways, but in this case "an essential or distinctive attribute or quality of a thing" fits best.
Think about the purpose of the action. Are you, in fact, altering or retrieving "an essential or distinctive attribute"? In your example, you are using a function to set a property of a textbox. That seems kind of silly, does it not?
Properties really are functions. They all compile down to getXXX() and setXXX(). It just hides them in syntactic sugar, but it's sugar that provides a semantic meaning to the process.
Think about properties like attributes. A car has many attributes. Color, MPG, Model, etc.. Not all properties are setable, some are calculatable.
Meanwhile, a Method is an action. GetColor should be a property. GetFile() should be a function. Another rule of thumb is, if it doesn't change the state of the object, then it should be a function. For example, CalculatePiToNthDigit(n) should be a function, because it's not actually changing the state of the Math object it's attached to.
This is maybe rambling a bit, but it really boils down to deciding what your objects are, and what they represent. If you can't figure out if it should be a property or function, maybe it doesn't matter which.
Properties should only be simple set and get one liners. Anything more and it should really be moved to a method. Complex code should always be in methods.
I only use properties for variable access, i.e. getting and setting individual variables, or getting and setting data in controls. As soon as any kind of data manipulation is needed/performed, I use methods.
As a matter of design Properties represent Data or Attributes of class object, While methods are actions or behaviors of class object.
In .Net, world there are other implications of using Properties:
Properties are used in Databinding, while get_ / set_ methods are not.
XML serialization user properties as natural mechanism of serilization.
Properties are accessed by PropertyGrid control and intern ICustomTypeDescriptor, which can be used effectively if you are writing a custom library.
Properties are controlled by Attributes, one can use it wisely to design Aspect Oriented softwares.
Misconceptions (IMHO) about Properties' usage:
Used to expose small calculations: ControlDesigner.SelectionRules's get block runs into 72 lines!!
Used to expose internal Data structures: Even if a property does not map to an internal data member, one can use it as property, if its an attribute of your class. Viceversa, even if its an attribute of your class properties are not advisable, to return array like data members (instead methods are used to return deep copy of members.)
In the example here it could have been written, with more business meaning as:
public String Title
{
set { Label.Text = text; }
}
Also big plus for Properties is that value of property can be seen in Visual Studio during debugging.
I prefer to use properties for add/set methods with 1 parameter. If parameters are more, use methods.
Properties are really nice because they are accessible in the visual designer of visual studio, provided they have access.
They use be used were you are merely setting and getting and perhaps some validation that does not access a significant amount of code. Be careful because creating complex objects during validation is not simple.
Anything else methods are the preferred way.
It's not just about semantics. Using properties inappropriate start having weirdness occur in the visual studio visual designer.
For instance I was getting a configuration value within a property of a class. The configuration class actually opens a file and runs an sql query to get the value of that configuration. This caused problems in my application where the configuration file would get opened and locked by visual studio itself rather than my application because was not only reading but writing the configuration value (via the setter method). To fix this I just had to change it to a method.
Here is a good set of guidelines for when to use properties vs methods from Bill Wagner
Use a Property when all these are true:
The getters should be simple and thus unlikely to throw exceptions. Note that this implies no network (or database) access. Either might fail, and therefore would throw an exception.
They should not have dependencies on each other. Note that this would include setting one property and having it affect another. (For example, setting the FirstName property would affect a read-only FullName property that composed the first name + last name properties implies such a dependency )
They should be settable in any order
The getter does not have an observable side effect Note this guideline doesn't preclude some forms of lazy evaluation in a property.
The method must always return immediately. (Note that this precludes a property that makes a database access call, web service call, or other similar operation).
Use a method if the member returns an array.
Repeated calls to the getter (without intervening code) should return the same value.
Repeated calls to the setter (with the same value) should yield no difference from a single call.
The get should not return a reference to internal data structures (See item 23). A method could return a deep copy, and could avoid this issue.
*Taken from my answer to a duplicate question.
This is simple.
1: use property when you want your data should be validated before storing in field. So in this way property provides encapsulation for your fields. Because if you leave your fields public end user may assign any value which may or may not be valid as per your business requirement like age should be greater than 18. So before value is store corresponding field we need to check its validity. In this way properties represent data.
2: Use method when you want perform some action like you are supplying some data as parameter and your method is doing some processing on the basis of supplied values and returning processed value as output. Or you want to change value of some field by this calculation. "In this way method represents action".
I come from java an i used get.. set.. method for a while.
When i write code, i don't ask to my self: "accessing this data is simple or require a heavy process?" because things can change (today retrive this property is simple, tomonrow can require some or heavy process).
Today i have a method SetAge(int age) tomonrow i will have also method SetAge(date birthdate) that calculate the age using the birthdate.
I was very disappointed that the compiler transform property in get and set but don't consider my Get... and Set.. methods as the same.

Categories