Home > OS >  How to call a non-static function when I cannot make the function itself static
How to call a non-static function when I cannot make the function itself static

Time:12-15

As part of a uni assignment, I need to create a self-checkout simulation in C# and add an additional function - in this case a clubcard points system.

I've created a Members class who will hold the points, but I'm trying to have my winforms UI display member name when the scan membership card button is clicked.

The GetName() function is below -

class Members
    {
        // Attributes
        protected int membershipID;
        protected string firstName;
        protected string lastName;
        protected int clubcardPoints;

        // Constructor
        public Members(int membershipID, string firstName, string lastName, int clubcardPoints)
        {
            this.membershipID = membershipID;
            this.firstName = firstName;
            this.lastName = lastName;
            this.clubcardPoints = clubcardPoints;
        }

        // Operations
        public string GetName()
        {
            string name = firstName   " "   lastName;
            return name;
        }
        ...
    }

And here is a snippet from the UpdateDisplay function in UserInterface.cs.

    void UpdateDisplay()
    {
        // DONE: use all the information we have to update the UI:
        //     - set whether buttons are enabled
        //     - set label texts
        //     - refresh the scanned products list box

        if (selfCheckout.GetCurrentMember() != null)
        {
            lblMember.Text = Members.GetName();
        }
        ...
     }

Members.GetName() can't be used because it isn't a static function, but I don't know if I can convert it into a static function. What would be the best way to get this working?

Appreciate any help, I hope it makes sense! Pretty new to this so I'm not sure if I'm wording it correctly.

CodePudding user response:

Can you call selfCheckout.GetCurrentMember().GetName()

CodePudding user response:

Members.GetName() can't be used because it isn't a static function

This error happens because GetName method is member of instance. But you call it as static member. To call it as instance member you should do like this:

var currentMember = selfCheckout.GetCurrentMember(); //to make both check for null and call methods, you should firstly create variable with this object
if (currentMember  != null)
{
    lblMember.Text = currentMember.GetName(); // if current member is not null, call GetName
}
  • Related