Reputation: 1520
I have a class called SerializableString
which extends a base class CustomXmlSerializable
. The base class provides methods for XML serializing and deserializing the derived class.
public class SerializableString : CustomXmlSerializable
{
public string String { get; set; }
}
Obviously, I can call the string
property anything I want. But because this class is so general in nature, it would be nice to give it a very obvious name like "String." This way, the property can be accessed as:
SerializableString userName = new SerializableString();
userName.String = "khargoosh";
The compiler allows this. Notwithstanding the nature of the class and property, would it be considered bad practice, or dangerous, to give the one and only property in the class the name "String" ?
Upvotes: 4
Views: 199
Reputation: 568
As Eric Lippert himself says here, this is "perfectly acceptable practice; the C# language has been carefully designed so that this is legal and practical."
Furthermore, in this case it seems unambiguous what your String property means: you have a class which is like a string, but serializable, and this property returns the underlying string. Suppose in fact that String
was not a primitive type, and the primitive type was str
or something. Then it does not seem to me that there would be any problem or ambiguity in calling this property (the central property of your class) simply "String" (with return type str
in my hypothetical case)
Upvotes: 0
Reputation: 17346
Don't do this, even though it's valid as far as the compiler is concerned. Eric Lippert's example of Color Color
is different - most things rarely have more than one color property so naming a property Color
usually tells you all you need to know about that property. I call this a valid case where using the type name (Color
) is fine to be used as the name of the property. (One could argue whether this is a good argument but in the past I had to deal with this exact problem and ended up using Color Color
.)
In the case of string String
you don't learn anything from the name of the property - a given object may have (and objects frequently do) several properties of type string
. Naming a property String
doesn't tell you anything about the purpose of that property. This makes the code harder to understand.
This is just a personal opinion - as the other answer points out, this is syntactically valid. At the end, this is a judgement call - I'd avoid naming a property after its type as much as possible. Longer, unique property / function names usually carry more information about the intended use of that symbol.
Specifically for this question, I'd call the property Value
:
public string Value { get; set; }
Upvotes: 4