Ben
Ben

Reputation: 39

C# declare Enum and use it in function but i got CS0120

i have a namespace called "NameSpace":

using System;
using System.Collections;

namespace NameSpace
{
    public enum Number
    {
        One,
        Two,
        Three
    }
    public sealed class Test1
    {
        public string test(Number num)
        {
            switch (num)
            {
                case Number.One:
                    return "1";
                case Number.Two:
                    return "2";
                case Number.Three:
                    return "3";
            }
            return "?";
        }
    }
}

and when I call this line :

Console.WriteLine(NameSpace.Test1.test(NameSpace.Number.One));

and I get a error :

error CS0120: An object reference is required to access non-static member `NameSpace.Test1.test(NameSpace.Number)'

Someone can help me ? thank you vary much !

Upvotes: 0

Views: 166

Answers (4)

Florensvb
Florensvb

Reputation: 207

You have to first make an object of class Test1 and then call the test method on it

Console.WriteLine(new Test1().test(NameSpace.Number.One));

Upvotes: 2

Marian Dolinský
Marian Dolinský

Reputation: 3492

This is happening because you've not declared the test method as static. You'll have to add the static keyword to the method declaration such as public static string test... or create new instance of the Test1 class.

Test1 t = new Test1();
Console.WriteLine(t.test(Number.One));

You should read more about static and object-oriented programming.

Upvotes: 0

René Vogt
René Vogt

Reputation: 43886

You have two options:

You can make test a `static method:

public static string test(Number num) { /*...*/ }

Then you don't need an instance of Test1 but an call test on the type:

Test1.test(Number.One);

Or you need to create an instance of your Test1 class:

Test1 instance = new Test1();
instance.test(Number.One);

Since the test method does not use any instance members of Test1, the first approach is sufficient.

Upvotes: 7

wkl
wkl

Reputation: 1894

You can do

Console.WriteLine(new NameSpace.Test1().test(NameSpace.Number.One));

or make the method static:

public static string test(Number num)

Upvotes: 3

Related Questions