-1

I want to write a small function but it gives a error: Error CS0120 An object reference is required for the non-static field, method, or property Program.WriteSlow(string, int)

using System;
using System.Threading;

namespace Dank_meemr
{
    class Program
    {
        int wordLength;
        static void Main(string[] args)
        {
            WriteSlow("Hello World!", 10);
        }
        public void WriteSlow(string text, int delay)
        {
            
            wordLength = text.Length;
            Console.Write(text[0]);
            for (int i = 0; i < wordLength; i++)
            {
                Console.Write(text[0 + 1]);
                Thread.Sleep(delay);
            }
        }


    }
}

How do you fix this?

  • Does this answer your question? [CS0120: An object reference is required for the nonstatic field, method, or property 'foo'](https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop) – MindSwipe Jun 22 '20 at 07:53
  • Just add `static` keyword to your function. –  Jun 22 '20 at 12:46

1 Answers1

2

In short, static methods and properties cannot access non-static fields and events in their containing type.

You will need to make your method static

public static void WriteSlow(string text, int delay)

Compiler Error CS0120

An object reference is required for the nonstatic field, method, or property 'member'

In order to use a non-static field, method, or property, you must first create an object instance. For more information about static methods, see Static Classes and Static Class Members. For more information about creating instances of classes, see Instance Constructors.


Additional Resources

Static Classes and Static Class Members (C# Programming Guide)

TheGeneral
  • 79,002
  • 9
  • 103
  • 141