using DateTime object inside enum - c#

I have this enum:
public enum TimePeriod
{
Day = DateTime.Now.AddDays(-1),
Week = DateTime.Now.AddDays(-7),
Month = DateTime.Now.AddMonths(-1),
AllTime = DateTime.Now
}
but cant do
(DateTime)timePeriod
how can i get the date given an enum?

In C#, the default underlying type for an enum is int, and unfortunately is only support basic data types like int, short, uint and so on. Therefore, storing the DateTimes inside an enum is not possible in .NET.
You can of course make a static class with static properties that expose the DateTimes you need instead of making it like an enum like this:
public static class TimePeriod
{
public static DateTime Day{ get{return DateTime.Now.AddDays(-1);}},
public static DateTime Week{ get{return DateTime.Now.AddDays(-7);}},
public static DateTime Month{ get{return DateTime.Now.AddMonths(-1);}},
public static DateTime AllTime{ get{return DateTime.Now;}},
}
And use it like this:
myDateTime = TimePeriod.Month;

In addition to Oyvind's answer. Enums Values have to be constant values and not variables.

You should use a class, not an enum for this.

Related

Return 2 values from a function?

I have an object that represents a scheduled payment. My database has a list of these payments, but I have one instance of a payment.
I need to write a method that gets the next payment after the one I have, as well as the previous date of the previous payment.
I'd like to write a method that return the two dates. But the return type of 'DateTime' only allows for one. I could return a List<DateTime> but that seems strange and ma be ambiguous. Which is the previous and which is the next?
I can also create a DTO object that has:
DateTime previousPayment {get; set;}
DateTime nextPayment {get; set;}
Tuple<DateTime, DateTime> might be another options, but it too is ambiguous. Unless I can name the properties of it?
But - is there a better way to allow for a method to return two dates? Anonymous types or something?
Use the "ref" modifier. (You may use "out" instead if you do not need to read the variable before it is assigned)
public void GetNextPayment(ref DateTime previousPayment, ref DateTime nextPayment){
// do stuff here
}
Usage:
DateTime previousPayment = DateTime.Now(); //Example
DateTime nextPayment = DateTime.Now(); // example
GetNextPayment(ref previousPayment, ref nextPayment); // Forgot to add "ref" when calling it
previousPayment and nextPayment will be modified in the function and maintain the value.
Update with Dictionary
As Anik mentioned, it might be better to use a Dictionary;
public Dictionary<string,DateTime> GetNextPayment(DateTime previousPayment, DateTime nextPayment){
// modify payments
Dictionary<string,DateTime> myDict = new Dictionary(string, DateTime);
myDict.Add("PreviousPayment", [date]);
myDict.Add("NextPayment", [date]);
return myDict;
}
Use Class
Ilya. N. mentioned to use a class. I would have to agree with this if you're going to have lots of payment objects going to be used more than once. But I firmly believe it's better to give you all the tools available at your disposal because you never know when you might want to use out parameters or Dictionaries.
public class Payment {
public string Name {get;set;}
public DateTime previousPayment {get;set;}
public DateTime nextPayment {get;set;}
public GetNextPayment(){
// code to get the next payment
this.previousPayment = //whatever
this.nextPayment = //whatever
}
}
If you only have ONE payment you are going to be using, like ever. (good to future proof with a class), then you might use a method or dictionary.
Besides the two options you listed, there are two more:
Return a Tuple<DateTime, DateTime>
Use out parameters
Why not simply return a class?
public class DateCombo {
DateTime PreviousPayment {get; set;}
DateTime NextPayment {get; set;}
}
try this ...
private void Form1_Load(object sender, EventArgs e)
{
DateTime previousPayment =new DateTime();
DateTime nextPayment=new DateTime();
getdate(ref previousPayment, ref nextPayment);
}
public void getdate(ref DateTime previousPayment, ref DateTime nextPayment)
{
previousPayment = System.DateTime.Now;
nextPayment = System.DateTime.Now.AddDays(1);
}

Identifier expected,String is a keyword

I have a php code like this,going to convert it in to C#.
function HuntingDate()
{
Global $nameofselectbox,$startYear,$endYear,$year,
$startDate,$endDate,$startMounth,$endMounth,$startDay,$endDay;
$today = getdate();
$year=$today['year'];
$mounth=$today['mon'];
$day=$today['mday'];
Here is my try( I tried to use enum for this)
public enum HuntingDate{string StartYear,string EndYear,string Year,string StartDate,string EndDate,string StartMonth,string EndMonth,stirng StartDay,string EndDay}
Can i do thisone with enum ? i got the error "Identifier expected,String is a keyword"
No not with enum, you should use a class for this:
public class HuntingDate
{
string StartYear;
string EndYear;
string Year;
string StartDate;
string EndDate;
string StartMonth;
string EndMonth;
string StartDay;
string EndDay;
}
you then have further things to consider:
Strings are not ideal for date type data, for this consider using DateTime - with this you can merge the year, month and day values into one property:
public class HuntingDate
{
public DateTime StartDateTime;
public DateTime EndDateTime;
}
Classes are used to define the structure of an object, as my example stands you would need to create an instance of the class in order to use it:
HuntingDate huntingDate = new HuntingDate();
with this you have to consider where you want to have access to it. If you need a global accessible instance you could initialise the class at a global scope level, or consider using a static class (though it should be noted that these values would be persisted across the whole application):
public static class HuntingDate
{
public static string Something;
}
I would strongly suggesting doing some reading on C# (get a book!) if you want to do this more seriously you should get a solid grasp of the basics of C#
I guess you want the (string) values "StartYear", "EndYear" and so on as values of an enum.
You cannot do that: an enum is always based on some integer type.
I think you would be better off using the DateTime type for the start and end dates, and wrap it all in a class something like this:
public class HuntingDate
{
public HuntingDate(DateTime start, DateTime end)
{
_start = start;
_end = end;
}
public DateTime End
{
get
{
return _end;
}
}
public DateTime Start
{
get
{
return _start;
}
}
private readonly DateTime _start;
private readonly DateTime _end;
}
No, You can do this with enum. By default the underlying type of each element in the enum is int.
You can specify another integral numeric type by using a colon, as
shown in the example below. For a full list of possible types, see enum (C#
Reference).
Example:
enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
You can use struct or class type for this purpose.
public struct HuntingDate
{
int StartYear;
int StartMonth;
int StartDay;
int Year;
DateTime StartDate; // it smells like you are storing date then why do
// you not use DateTime rather than these..
DateTime EndDate;
int EndYear;
int EndMonth;
int EndDay;
}
If your Year it not necessary then it can be shorten as:
public struct HuntingDate
{
public DateTime StartDate;
public DateTime EndDate;
}
other wise go for the full values including Year.
bear i mind i don't know php from... well php...
function HuntingDate()
{
Global $nameofselectbox,$startYear,$endYear,$year,
$startDate,$endDate,$startMounth,$endMounth,$startDay,$endDay;
$today = getdate();
$year=$today['year'];
$mounth=$today['mon'];
$day=$today['mday'];
... rest of code
}
I'm guesstimating you'll need a class (and not an enum)
public class HuntingDate()
{
string NameOfSelectbox;
DateTime endDate;
rest of code ...
}
I saw there are lots of answers,WHAT IS THE BEST ANSWER ?

Formatting dates when serialising an object in C# (2.0)

I'm xml-serializing a object with a large number of properties and I have two properties with DateTime types. I'd like to format the dates for the serialized output. I don't really want to implement the IXmlSerializable interface and overwrite the serialization for every property. Is there any other way to achieve this?
(I'm using C#, .NET 2)
Thanks.
For XML serialization you would have to implement IXmlSerializable and not ISerializable.
However you can workaround this by using a helper property and by marking the DateTime properties with the XmlIgnore attribute.
public class Foo
{
[XmlIgnore]
public DateTime Bar { get; set; }
public string BarFormatted
{
get { return this.Bar.ToString("dd-MM-yyyy"); }
set { this.Bar = DateTime.ParseExact(value, "dd-MM-yyyy", null); }
}
}
You can use a wrapper class/struct for DateTime that overrides ToString method.
public struct CustomDateTime
{
private readonly DateTime _date;
public CustomDateTime(DateTime date)
{
_date = date;
}
public override string ToString()
{
return _date.ToString("custom format");
}
}

Using an Enum as an Attribute Argument

Here is the code I would like to use:
public enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };
[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }
EnumHelper looks like:
[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
public Type MyEnum { get; set; }
public EnumHelper(Type enum)
{
MyEnum = enum;
}
}
The error I get on EnumHelper(Days) is that "Enum Name not valid at this point". Am I doing something wrong, or can this not be done?
MORE INFO
I am trying to pass the Enum (Days), and randomly get back one of the values.
You're trying to pass a type name as if it were an argument value. You can't do that. However, you can do:
[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
public Type EnumType;
public EnumHelper(Type enumType)
{
EnumType = enumType;
}
}
...
[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }
However:
I wouldn't personally make EnumType a public field; make it a property.
There's currently no validation that EnumType is actually an enum. You can't do it at compile-time, but you could do it at execution time.
For the sake of convention, it should be called EnumHelperAttribute (or something more descriptive, really) - this isn't causing the error, but it's more idiomatic
I'm not really sure I see the benefit... you can find the type of the property from the metadata already; what do you think the attribute is actually buying you?
If you could let us know what you're trying to accomplish, we may be able to be more useful to you.
The parameters in Attributes can be only constants.
If you want pass the enum type you must pass only the type:
[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }
[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
public Type MyEnum;
public EnumHelper(Type enum)
{
MyEnum = enum;
}
}
The parameter should be an enum value, not an enum type, like:
[EnumHelper(Days.Sat)]
Just wanted to add how I ran into this and fixed it. I had my property named the same as my enumeration. The code would compile and run, but I was getting a the red line error message in the IDE. Changing the name of the property to something unique cleared the message.

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

Does any one know how I can specify the Default value for a DateTime property using the System.ComponentModel DefaultValue Attribute?
for example I try this:
[DefaultValue(typeof(DateTime),DateTime.Now.ToString("yyyy-MM-dd"))]
public DateTime DateCreated { get; set; }
And it expects the value to be a constant expression.
This is in the context of using with ASP.NET Dynamic Data. I do not want to scaffold the DateCreated column but simply supply the DateTime.Now if it is not present. I am using the Entity Framework as my Data Layer
Cheers.
You cannot do this with an attribute because they are just meta information generated at compile time. Just add code to the constructor to initialize the date if required, create a trigger and handle missing values in the database, or implement the getter in a way that it returns DateTime.Now if the backing field is not initialized.
public DateTime DateCreated
{
get
{
return this.dateCreated.HasValue
? this.dateCreated.Value
: DateTime.Now;
}
set { this.dateCreated = value; }
}
private DateTime? dateCreated = null;
Add below to the DateTime property
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
I have tested this on EF core 2.1
Here you cannot use either Conventions or Data Annotations. You must use the Fluent API.
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Created)
.HasDefaultValueSql("getdate()");
}
}
Official doc
There's no reason I can come up with that it shouldn't be possible to do through an attribute. It might be in Microsoft's backlog. Who knows.
The best solution I have found is to use the defaultValueSql parameter in the code first migration.
CreateTable(
"dbo.SomeTable",
c => new
{
TheDateField = c.DateTime(defaultValueSql: "GETDATE()")
});
I don't like the often reference solution of setting it in the entity class constructor because if anything other than Entity Framework sticks a record in that table, the date field won't get a default value. And the idea of using a trigger to handle that case just seems wrong to me.
It is possible and quite simple:
for DateTime.MinValue
[System.ComponentModel.DefaultValue(typeof(DateTime), "")]
for any other value as last argument of DefaultValueAttribute specify string that represent desired DateTime value.
This value must be constant expression and is required to create object (DateTime) using TypeConverter.
Just found this looking for something different, but in the new C# version, you can use an even shorter version for that:
public DateTime DateCreated { get; set; } = DateTime.Now;
A simple solution if you are using the Entity Framework is the add a partical class and define a constructor for the entity as the framework does not define one. For example if you have an entity named Example you would put the following code in a seperate file.
namespace EntityExample
{
public partial class Example : EntityObject
{
public Example()
{
// Initialize certain default values here.
this._DateCreated = DateTime.Now;
}
}
}
I think the easiest solution is to set
Created DATETIME2 NOT NULL DEFAULT GETDATE()
in column declaration and in VS2010 EntityModel designer set corresponding column property StoreGeneratedPattern = Computed.
Creating a new attribute class is a good suggestion. In my case, I wanted to specify 'default(DateTime)' or 'DateTime.MinValue' so that the Newtonsoft.Json serializer would ignore DateTime members without real values.
[JsonProperty( DefaultValueHandling = DefaultValueHandling.Ignore )]
[DefaultDateTime]
public DateTime EndTime;
public class DefaultDateTimeAttribute : DefaultValueAttribute
{
public DefaultDateTimeAttribute()
: base( default( DateTime ) ) { }
public DefaultDateTimeAttribute( string dateTime )
: base( DateTime.Parse( dateTime ) ) { }
}
Without the DefaultValue attribute, the JSON serializer would output "1/1/0001 12:00:00 AM" even though the DefaultValueHandling.Ignore option was set.
Simply consider setting its value in the constructor of your entity class
public class Foo
{
public DateTime DateCreated { get; set; }
public Foo()
{
DateCreated = DateTime.Now;
}
}
using System.ComponentModel.DataAnnotations.Schema;
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreatedOn { get; private set; }
I needed a UTC Timestamp as a default value and so modified Daniel's solution like this:
[Column(TypeName = "datetime2")]
[XmlAttribute]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[Display(Name = "Date Modified")]
[DateRange(Min = "1900-01-01", Max = "2999-12-31")]
public DateTime DateModified {
get { return dateModified; }
set { dateModified = value; }
}
private DateTime dateModified = DateTime.Now.ToUniversalTime();
For DateRangeAttribute tutorial, see this awesome blog post
There is a way. Add these classes:
DefaultDateTimeValueAttribute.cs
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Custom.Extensions;
namespace Custom.DefaultValueAttributes
{
/// <summary>
/// This class's DefaultValue attribute allows the programmer to use DateTime.Now as a default value for a property.
/// Inspired from https://code.msdn.microsoft.com/A-flexible-Default-Value-11c2db19.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class DefaultDateTimeValueAttribute : DefaultValueAttribute
{
public string DefaultValue { get; set; }
private object _value;
public override object Value
{
get
{
if (_value == null)
return _value = GetDefaultValue();
return _value;
}
}
/// <summary>
/// Initialized a new instance of this class using the desired DateTime value. A string is expected, because the value must be generated at runtime.
/// Example of value to pass: Now. This will return the current date and time as a default value.
/// Programmer tip: Even if the parameter is passed to the base class, it is not used at all. The property Value is overridden.
/// </summary>
/// <param name="defaultValue">Default value to render from an instance of <see cref="DateTime"/></param>
public DefaultDateTimeValueAttribute(string defaultValue) : base(defaultValue)
{
DefaultValue = defaultValue;
}
public static DateTime GetDefaultValue(Type objectType, string propertyName)
{
var property = objectType.GetProperty(propertyName);
var attribute = property.GetCustomAttributes(typeof(DefaultDateTimeValueAttribute), false)
?.Cast<DefaultDateTimeValueAttribute>()
?.FirstOrDefault();
return attribute.GetDefaultValue();
}
private DateTime GetDefaultValue()
{
// Resolve a named property of DateTime, like "Now"
if (this.IsProperty)
{
return GetPropertyValue();
}
// Resolve a named extension method of DateTime, like "LastOfMonth"
if (this.IsExtensionMethod)
{
return GetExtensionMethodValue();
}
// Parse a relative date
if (this.IsRelativeValue)
{
return GetRelativeValue();
}
// Parse an absolute date
return GetAbsoluteValue();
}
private bool IsProperty
=> typeof(DateTime).GetProperties()
.Select(p => p.Name).Contains(this.DefaultValue);
private bool IsExtensionMethod
=> typeof(DefaultDateTimeValueAttribute).Assembly
.GetType(typeof(DefaultDateTimeExtensions).FullName)
.GetMethods()
.Where(m => m.IsDefined(typeof(ExtensionAttribute), false))
.Select(p => p.Name).Contains(this.DefaultValue);
private bool IsRelativeValue
=> this.DefaultValue.Contains(":");
private DateTime GetPropertyValue()
{
var instance = Activator.CreateInstance<DateTime>();
var value = (DateTime)instance.GetType()
.GetProperty(this.DefaultValue)
.GetValue(instance);
return value;
}
private DateTime GetExtensionMethodValue()
{
var instance = Activator.CreateInstance<DateTime>();
var value = (DateTime)typeof(DefaultDateTimeValueAttribute).Assembly
.GetType(typeof(DefaultDateTimeExtensions).FullName)
.GetMethod(this.DefaultValue)
.Invoke(instance, new object[] { DateTime.Now });
return value;
}
private DateTime GetRelativeValue()
{
TimeSpan timeSpan;
if (!TimeSpan.TryParse(this.DefaultValue, out timeSpan))
{
return default(DateTime);
}
return DateTime.Now.Add(timeSpan);
}
private DateTime GetAbsoluteValue()
{
DateTime value;
if (!DateTime.TryParse(this.DefaultValue, out value))
{
return default(DateTime);
}
return value;
}
}
}
DefaultDateTimeExtensions.cs
using System;
namespace Custom.Extensions
{
/// <summary>
/// Inspired from https://code.msdn.microsoft.com/A-flexible-Default-Value-11c2db19. See usage for more information.
/// </summary>
public static class DefaultDateTimeExtensions
{
public static DateTime FirstOfYear(this DateTime dateTime)
=> new DateTime(dateTime.Year, 1, 1, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
public static DateTime LastOfYear(this DateTime dateTime)
=> new DateTime(dateTime.Year, 12, 31, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
public static DateTime FirstOfMonth(this DateTime dateTime)
=> new DateTime(dateTime.Year, dateTime.Month, 1, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
public static DateTime LastOfMonth(this DateTime dateTime)
=> new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month), dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
}
}
And use DefaultDateTimeValue as an attribute to your properties. Value to input to your validation attribute are things like "Now", which will be rendered at run time from a DateTime instance created with an Activator. The source code is inspired from this thread: https://code.msdn.microsoft.com/A-flexible-Default-Value-11c2db19. I changed it to make my class inherit with DefaultValueAttribute instead of a ValidationAttribute.
I faced the same issue, but the one which works for me best is below:
public DateTime CreatedOn { get; set; } = DateTime.Now;
In C# Version 6 it's possible to provide a default value
public DateTime fieldname { get; set; } = DateTime.Now;
Using EntityTypeConfiguration, I get it like this:
public class UserMap : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
//throw new NotImplementedException();
builder.Property(u => u.Id).ValueGeneratedOnAdd();
builder.Property(u => u.Name).IsRequired().HasMaxLength(100);
builder.HasIndex(u => u.Email).IsUnique();
builder.Property(u => u.Status).IsRequired();
builder.Property(u => u.Password).IsRequired();
builder.Property(u => u.Registration).HasDefaultValueSql("getdate()");
builder.HasMany(u => u.DrawUser).WithOne(u => u.User);
builder.ToTable("User");
}
}
Using the Fluent API, in OnModelCreating function in your Context class add following.
builder.Property(u => u.CreatedAt).ValueGeneratedOnAdd();
builder.Property(u => u.UpdatedAt).ValueGeneratedOnAddOrUpdate();
Note I'm using a separate type configuration class. If you did right in the function would be like:
builder.Enitity<User>().Property(u => u.CreatedAt).ValueGeneratedOnAdd();
public DateTime DateCreated
{
get
{
return (this.dateCreated == default(DateTime))
? this.dateCreated = DateTime.Now
: this.dateCreated;
}
set { this.dateCreated = value; }
}
private DateTime dateCreated = default(DateTime);
How you deal with this at the moment depends on what model you are using Linq to SQL or EntityFramework?
In L2S you can add
public partial class NWDataContext
{
partial void InsertCategory(Category instance)
{
if(Instance.Date == null)
Instance.Data = DateTime.Now;
ExecuteDynamicInsert(instance);
}
}
EF is a little more complicated see http://msdn.microsoft.com/en-us/library/cc716714.aspx for more info on EF buisiness logic.
I know this post is a little old, but a have a suggestion that may help some.
I used an Enum to determine what to set in the attribute constructor.
Property declaration :
[DbProperty(initialValue: EInitialValue.DateTime_Now)]
public DateTime CreationDate { get; set; }
Property constructor :
Public Class DbProperty Inherits System.Attribute
Public Property InitialValue As Object
Public Sub New(ByVal initialValue As EInitialValue)
Select Case initialValue
Case EInitialValue.DateTime_Now
Me.InitialValue = System.DateTime.Now
Case EInitialValue.DateTime_Min
Me.InitialValue = System.DateTime.MinValue
Case EInitialValue.DateTime_Max
Me.InitialValue = System.DateTime.MaxValue
End Select
End Sub
End Class
Enum :
Public Enum EInitialValue
DateTime_Now
DateTime_Min
DateTime_Max
End Enum
I think you can do this using StoreGeneratedPattern = Identity (set in the model designer properties window).
I wouldn't have guessed that would be how to do it, but while trying to figure it out I noticed that some of my date columns were already defaulting to CURRENT_TIMESTAMP() and some weren't. Checking the model, I see that the only difference between the two columns besides the name is that the one getting the default value has StoreGeneratedPattern set to Identity.
I wouldn't have expected that to be the way, but reading the description, it sort of makes sense:
Determines if the corresponding column in the database will be auto-generated during insert and update operations.
Also, while this does make the database column have a default value of "now", I guess it does not actually set the property to be DateTime.Now in the POCO. This hasn't been an issue for me as I have a customized .tt file that already sets all of my date columns to DateTime.Now automatically (it's actually not hard to modify the .tt file yourself, especially if you have ReSharper and get a syntax highlighting plugin. (Newer versions of VS may already syntax highlight .tt files, not sure.))
The issue for me was: how do I get the database column to have a default so that existing queries that omit that column will still work? And the above setting worked for that.
I haven't tested it yet but it's also possible that setting this will interfere with setting your own explicit value. (I only stumbled upon this in the first place because EF6 Database First wrote the model for me this way.)
below works in .NET 5.0
private DateTime _DateCreated= DateTime.Now;
public DateTime DateCreated
{
get
{
return this._DateCreated;
}
set { this._DateCreated = value; }
}
You can also consider using the DatabaseGenerated attribute, example
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime DateCreated { get; set; }
https://learn.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=data-annotations
I also wanted this and came up with this solution (I'm only using the date part - a default time makes no sense as a PropertyGrid default):
public class DefaultDateAttribute : DefaultValueAttribute {
public DefaultDateAttribute(short yearoffset)
: base(DateTime.Now.AddYears(yearoffset).Date) {
}
}
This just creates a new attribute that you can add to your DateTime property.
E.g. if it defaults to DateTime.Now.Date:
[DefaultDate(0)]

Categories