When defining the default value, what is the difference between
[DefaultValue("member")]
public string Role { get; set; }
and
public string Role { get; set; } = "member";
The first is an attribute which can be useful for meta-programming. For example, you might want to remember what the default value is if someone clears an input. It has nothing to do with the C# language itself. It does not modify the value of Role.
The second actually sets the property's value to 'member' in memory.
From the documentation:
A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
In other words, your first example helps tools (like the Windows Forms Designer) to know what the intended default value for a property is. But it does nothing at run-time.
If you want a property to be assigned a default value at run-time, you have to do it yourself, as in the second example you show.
Related
I have to handle following validation scenario:
If Some condition is met then we're displaying textbox which should be mandatory
If not met value for the property should be optional
Model Looking kind of this:
public class Setting
{
[Required]
public string Domain { get; set; }
}
Is that possible to differentiate somehow when field value was omitted or it didn't bind? Cause as I know if the value was omitted or not bound the value of it would be a default(string). In this case, I'm not able to definite should Domain be provided or not
If you have situations where it may or may not be required, you're best bet may be to have your Setting class inherit from IValidatableObject and implement your own Validate() method. Do whatever checksyou need to to see if it's required or not and do a yield return new ValidationResult("Description", new[] { nameof(Domain ) }) to explain why it's not valid.
If you can't make that determination inside your Settings class, then you'll likely have to do it in your controller action, and use something like ModelState.AddModelError("Description", nameof(model.Domain))); followed by checking ModelState.IsValid to see if the action should kick out and return a redirect/view
I am using CommandLine Parser Library to parse command line arguments within an application.
There are some options that will in most cases be the same every time a user runs the application. Usually, I use the DefaultValue attribute so that if the user does not provide a value a default one will be used.
[Option('a', "address", DefaultValue = "http://me.com", Required = false, HelpText = "Address of server.")]
public string Address{ get; set; }
The issue I am facing is that the default value is specific for a given deployment and needs to be configured after deployment. I would like the user/administrator to be able to set the default value of these options using a configuration file.
Does anyone know how to change the default value for an option at run time? Then when starting the application I can load the configuration file and set the default values accordingly.
For the benefit of anyone else looking for this, I was facing the same issue today, and I realised that Options work fine with C# 6 Auto Property Initializers.
[Option]
public string MyProperty { get; set; } = Properties.Settings.Default.MySetting;
No doubt in C# 5 and earlier you could achieve the same thing with a private backing property.
I would create the properties as Application Settings, then allow the user to override them with command line arguments and calculate the resulting values at runtime.
This way you have compiled default values, possibilities for the user to override with custom defaults in the config file and a way to set one-time overrides at startup.
I have a class member marked as [DataMember(IsRequired=false)], and I'd like to know if a value for this particular member was specified inside the original message. For example,
[DataContract]
public class Person
{
[DataMember]
public String Name { get; set; }
[DataMember(IsRequired=false)]
public DateTime BirthDate { get; set; }
}
If I deserialize a the following message using the DataContractSerializer, how can I know that the optional member BirthDate was not specified?
<Person>
<Name>Carlos</Name>
</Person>
I know for the XmlSerializer there is the Specified pattern for flagging if a member was included inside the message being deserialized. Is there any equivalent for DataContractSerializer?
First of all, you don't need to set IsRequired to false explicitly. By default, it's already false.
Another issue is that EmitDefaultValue is -- by default -- set to true. As a result, a value for DateTime will always be emitted, even if you never set it on serialization time. This value will be default(DateTime.) Similarly, a value for DateTime will always be set on deserialization time, even if it's not even on the wire!
As a result, you can't even tell if something was on the wire or not, at all, out of the box.
But you have several options here. It's extra work but worth it.
Check if the date time is deserialized and set to default(DateTime.) If you know for sure that your application will never set the date to default(DateTime), this lets you know that the date wasn't actually present on the wire.
Another option you have is to encapsulate the DateTime in a reference type. Since reference types are null if not present, that lets you know right away if a DateTime was present or not (because the encapsulating reference type would be either non-null or null.)
Yet another option is to use a nullable date time DataMember (i.e., the type would be "DateTime?" instead of "DateTime".)
A final option you have is to add an extra complementary variable (perhaps a boolean) that is set on OnDeserializing/OnDeserialized/OnSerializing/OnSerialized and use this to track whether or not something was actually present on the wire. You might, for example, set this complementary variable to true only when you're actually serializing out a date time.
I have been using mvc2 for a while now, and when i need to set the template i use the DataType Attribute
[DataType("DropDown")]
public int Field { get; set; }
I see others using UiHint to achieve the same results
[UiHint("DropDown")]
public int Field { get; set; }
What is the difference between using these two attributes? Which attribute should I be normally using, or are they for different tasks?
DataType is generally used to make it known that this is a very specific version of a property, such as price.
The most common example of DataType is the [DataType(DataTypes.EmailAddress)] which usually is a string but we're saying that this is a very specific type of string.
They're both helpful and the UIHint overrides the DataType. So if you have a certain DataType but you want to override the editor for that specific property you can use a UIHint.
DataType attribute has two purposes
Provide additional type information for a data field. You do this by applying the DataTypeAttribute attribute to a data field in the data model and by specifying the additional type name from the DataType enumeration. Then the view engine uses the default template for displaying the property, like, a checkbox for a boolean.
If you want to override the default template, and wish to use a custom template, then it can be used to associate a custom field template with that data field. In this case you must provide a partial page[.cshtml, MVC 4] to describe the display.
The purpose of UIHint is exactly same as the second point above.
Where to use what? The answer is: context, ie., what will make more sense, what is closer to the physical problem your code is trying to solve.
What if both are applied to the same property? The answer is: UIHint has precedence, obviously. But why would you apply both?
I am trying to build a web user control and set some default values for its properties in the code-behind like this:
[DefaultValue(typeof(int), "50")]
public int Height { get; set; }
[DefaultValue(typeof(string), "string.Empty")]
public string FamilyName { get; set; }
[DefaultValue(typeof(Color), "Orange")]
public System.Drawing.Color ForeColor { get; set; }
When I add the user control to the page and call it without any properties:
<uc1:Usercontrol ID="uc" runat="server" />
the default values are not set and every property is 0 or null.
What am I doing wrong?
Thanks.
The DefaultValueAttribute will not set any value for your property, it only serves as a hint for designers and whatnot.
If you want a default value, you'll have to set it in the constructor (or even better, in a property initializer, which were added in C# 6). If you're storing your stuff in the ViewState, you'll need to expand those property definitions and make them access the ViewState. Then set the default values for the properties in the OnInit method to avoid persisting them on the client side.
From http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
Note
A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
In other words, the DefaultValueAttribute just gives you a place to declare what you want the value to be. You still have to write code to populate the value from the attribute.