3

I'm trying to understand concept "class" and write some easy program. But my function Check() is not correct. Please follow me to the right side..

namespace ConsoleApplication2
{
    public class Task
    {
        public string RusVer { get; set; } 
        public string Key { get; set; } 
        public string UserVer { get; set; }


        public void Check()
        {
            if (UserVer == Key)
                Console.WriteLine("Good");            
        }
    }

class Program
{
    static void Main(string[] args)
    {

        Task p1 = new Task();
        p1.RusVer = "Привет, Мир!";
        p1.Key = "Hello, World!";
        Console.WriteLine(p1.RusVer);
        Console.WriteLine("Translate it: ");
        p1.UserVer = Convert.ToString(Console.ReadLine());
        Console.WriteLine(p1.UserVer);

        Task.Check(); //errorCS0120

    }
}
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Eluvium
  • 163
  • 1
  • 4
  • 17

2 Answers2

6

You're calling Check as if it was static method. It is instance method so it should called p1.Check().

empi
  • 15,755
  • 8
  • 62
  • 78
  • then p1 - is a instance method? And if i write public static void Check() i must calling Task.Check()? – Eluvium Oct 19 '13 at 20:29
  • Check is an instance method (method called on instance of a type). p1 is an instance. – empi Oct 19 '13 at 20:30
4

Compiler Error CS0120: An object reference is required for the nonstatic field, method, or property 'member'

So In order to use a non-static field, method, or property, you must first create an object instance of a class

You need to call it with the help of Task class object

p1.Check();

If you declared Check() method as static then you can call it as you are currently doing.

 public static void Check()
 {
    if (UserVer == Key)
        Console.WriteLine("Good");            
 }
Sachin
  • 40,216
  • 7
  • 90
  • 102