Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An Object Reference is Required (GetWeekOfYear)

Tags:

c#

I keep being told this when I try to use the method:

An object reference is required for the non-static field, method, or property 'System.Globalization.Calendar.GetWeekOfYear(System.DateTime, System.Globalization.CalendarWeekRule, System.DayOfWeek)'

private static int GetWeekNumber(DateTime time)
{
    int week = GregorianCalendar.GetWeekOfYear(time, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
    return week;
}

And I can't seem to figure out why. What am I missing?

like image 289
OmniOwl Avatar asked Aug 01 '26 16:08

OmniOwl


1 Answers

GregorianCalendar need to be instanced then you can call the method

private static int GetWeekNumber(DateTime time)
{
    GregorianCalendar cal = new GregorianCalendar();
    int week = cal.GetWeekOfYear(time, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
    return week;
}

When you use the class name followed by a method name then that method should be defined as static by the class developer (to make it available without an instance). That's not the case with GetWeekOfYear. This method is an instance method thus you need an instance of the GregorianCalendar class.

C# reference: static vs instance methods

like image 179
Steve Avatar answered Aug 04 '26 06:08

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!