Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in my main program I am trying to use
C#
stack.createStack(40);


in stack class I have this function
C#
public void createStack(object value)
       {
           stack S = new stack();
           head = new Node();
           head.Cont = value;
           size++;


       }


I am just trying to make a constructor function which will creare a new stack, stack defined like this
C#
<pre>public List<int> stacklist;
        public class Node
        {
            public object Cont;
            public Node Next;

        }
        public Node head;

        public stack()
        {
            head = null;
        }
        public stack(object value)
        {
            head = new Node();
            head.Cont = value;

        }

I get the error:
Error	CS0120	An object reference is required for the non-static field, method, or property 'stack.createStack(object)'	Lists	


What I have tried:

I have no idea what to do next or how to avoid this
Posted
Updated 20-Feb-19 7:13am
Comments
Richard Deeming 20-Feb-19 13:28pm    
The createStack method creates a new stack instance, and throws it away. It then creates a new Node instance, stores the parameter in a field on that node, and then throws the node away. In then increments a size variable, which is not shown here.

You're also using camelCasing for types and methods, which goes against the naming guidelines[^]. Types, properties, and methods should use PascalCasing; you should only use camelCasing for parameters.

Combined with your confusion over static versus instance members, that suggests you would probably benefit from reviewing some introductory tutorials. For example:
Introduction to C# - interactive tutorials | Microsoft Docs[^]

1 solution

Try adding static like this :
C#
public static void createStack(object value)
{
    stack S = new stack();
    head = new Node();
    head.Cont = value;
    size++;
}

or using your class as follows if static is not what you need and your class has state :
C#
var s = new stack();
s.createStack(40);
 
Share this answer
 
v2
Comments
Member 14157091 20-Feb-19 14:36pm    
Thank you very much, it worked :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900