Hey I have a class and I want to add static field to it. I would like to determine value of this field in the block of code, sth like this:
public class MyClass
...
public static DateTime Date
{
int year = 2022;
int month = 1;
int day = 31;
Date = new DateTime(year, month, day);
}
How can I do that?
CodePudding user response:
You could also use a static constructor: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
CodePudding user response:
It's a bit unclear exactly what you want to do, but if you want a static property with a hardcoded value, this is a way to do it:
public class MyClass {
public static DateTime Date => new DateTime(2022, 1, 31);
}
CodePudding user response:
Static fields doesn't belong to the instance of a type, but rather to the type itself (so to speak) so you can not initialize the static fields by using instance members.
If you want to initialize the field you mentioned and hide the other fields you used to initialize it you could do something like this:
public class MyClass
{
public static MyDate Date = new MyDate(2022, 1, 31);
}
public class MyDate
{
public MyDate(int year, int month, int day)
{
Date = new DateTime(year, month, day);
}
public DateTime Date { get; }
}
I created here separate class to represent "my date" with the "initialization fields" I want in the constructor so no one can access or see them.
But you don't need to do this, instead you could just define a static property DateTime
and pass the initialization values from a static constructor in the type MyClass
.