Click here to Skip to main content
15,889,868 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I know this is a commonly asked question and i have tried following other answers to get my code to work but im having no luck. I have created an instance of the class (well itleast i thought i had) but im still getting the error "an object is required for nonstatic method"

What I have tried:

namespace Website.Forms
{
    public partial class AddDDPayment : PageBase<Add_DDPayment_Controller>
    {

        public PageMode Mode = PageMode.Add;

        public TextBox SortCode => tb_strsortcode;
        public TextBox Person => tb_nameonaccount;
        public TextBox BACSReference => tb_bacsreference;
        public TextBox AccountNumber => tb_straccountnumber;
        public TextBox BankName => tb_bankname;
        public TextBox BankAddress1 => tb_bankaddressline1;
        public TextBox BankAddressLine2 => tb_bankaddressline2;
        public TextBox BankAddressCity => tb_bankaddresscity;
        public TextBox BankAddressCountry => tb_bankaddresscountry;
        public TextBox BankAddressPostcode => tb_bankaddresspostcode;
        public TextBox BillingAddress1 => tb_billingaddress1;
        public TextBox BilingAddress2 => tb_billingaddress2;
        public TextBox BillingAddress3 => tb_billingaddress3;
        public TextBox BillingPostcode => tb_billingaddresspostcode;
        public CheckBox IsOwnBank => cb_isownbankaccount;


        public Button Update => btn_Update;
        public Button Close => btn_Close;

        public Label ErrorMessage => l_error;
        public Label InfoMessage => l_info;

        public virtual string Id
        {
            get => Request.QueryString["id"];
            set => throw new NotImplementedException();
        }

        public virtual object PersonId
        {
            get => ViewState["personId"];
            set => ViewState["personId"] = value;
        }

        public virtual object GroupId
        {
            get => ViewState["groupId"];
            set => ViewState["groupId"] = value;
        }


        protected void UpdateBankAddress(object sender, EventArgs e)
        {
            string sortCode = SortCode.Text;
            string accountNum = AccountNumber.Text;

            Helper h = new Helper();
            h.NewBankAddress(sortCode, accountNum);
        }
    }

    public class Helper
    {
        public string NewBankAddress(string sortCode, string accountNum)
        {
            PostcodeAnywhereBusinessLogic.ValidateBank(sortCode, accountNum);
            return "test";
        }
    }

}
Posted
Updated 25-Sep-19 16:22pm
Comments
F-ES Sitecore 23-Sep-19 6:34am    
On what line?
Member 12285600 23-Sep-19 6:35am    
PostcodeAnywhereBusinessLogic.ValidateBank(sortCode, accountNum);
F-ES Sitecore 23-Sep-19 6:56am    
That implies PostcodeAnywhereBusinessLogic is a type name rather than a variable, and you can only call methods on types if they are static, so that code will only work if ValidateBank is static. If it isn't then you need to call the method on an instance of the type, not the type itself;

PostcodeAnywhereBusinessLogic pcaLogic = new PostcodeAnywhereBusinessLogic();
pcaLogic.ValidateBank(sortCode, accountNum);
CPallini 23-Sep-19 6:34am    
In which line does the erro occurr?
Member 12285600 23-Sep-19 6:36am    
Sorry i should have mentioed im getting the error on line -

PostcodeAnywhereBusinessLogic.ValidateBank(sortCode, accountNum);

The message is saying that the <pre>PostcodeAnywhereBusinessLogic.ValidateBank</pre> method is non-static, which means it needs an instance of the PostcodeAnywhereBusinessLogic class in order to be called.

Let's think about cars for a moment: your Car has a GloveBox into which you put your mobile phone, and then you go down the pub. While in the pub, can you get hold of your mobile by opening a generic GloveBox on the bar and reaching in?
Of course not - you know that to get your mobile, you have to leave the pub, find your car - not any car, not my car: it has to be your car - open the door, open the GloveBox. and pick up your phone.

Your Car is an instance of the "Car class" and every instance has its own GloveBox - so when you want your phone you have to reference the actual instance contains the GloveBox that you opened to put your phone in.

PostcodeAnywhereBusinessLogic.ValidateBank if the same: you need to provide the exact instance of PostcodeAnywhereBusinessLogic that applies to the bank you want to validate.

And since we have no idea or access to the PostcodeAnywhereBusinessLogic class, you will have to work that out for yourself!
 
Share this answer
 
v2
I suggest you read up on Object and Collection Initializers - C# Programming Guide | Microsoft Docs[^] Note that in your case, your :
PostcodeAnywhereBusinessLogic.ValidateBank(sortCode, accountNum);
does not exist in the same class as you are using to make the call.

You could either make the object which you are calling static, or you will need to instantiate a new object of that classes object by doing something like :
PostcodeAnywhereBusinessLogic postcodeAnywhereBusinessLogic = new PostcodeAnywhereBusinessLogic(); 
And then you can call
postcodeAnywhereBusinessLogic.ValidateBank(sortCode, accountNum);
The following is a crude little application I made for you to test, debug, and learn from, and reading on from this point is optional. Something to note when instantiating objects, and working with statics, and I will use Interfaces as an example here.

If the class that needs instantiating has had values previously set on said object from within its own scope or by another class and when you call new on an object instance, you are creating a new object with all of its defined variables, methods and properties also as new. Let me show you. Notice in our base class, we have :
MessageClassA a = new MessageClassA();
MessageClassB b = new MessageClassB();
If you were to compare them, you will find they are identical (Except for the inner text to identify between each method), or until one of them are changed, or are sent separate parameters. "a" is a new object derivative of MessageClassA, as is "b" for MessageClassB.

By instantiating a new object type, you will be contracting with the new object you just created. And so; any newly created objects with property variables set on object "a" have no effect on object "b" as it is not the same instance body as it was defined with, but a completely new one. For example Paste this code into a test application and you will get a feel for what is happening. Starting with our base class :
public class BaseClass
{
    public string XValue { get; set; } = "DefaultValue";
    public void ExecuteMe()
    {
        MessageClassA a = new MessageClassA();
        MessageClassB b = new MessageClassB();
        LogMessage logMessage = new LogMessage();
        BaseClass baseClass = new BaseClass();
        baseClass.XValue = "foo";
        logMessage.WriteMessage(a, XValue);
        logMessage.WriteMessage(b, baseClass.XValue);
    }
}
Next we will add our interface which will do the talking for us.
public interface IMessageInterface
{
    void WriteMessage(string s);
}

Then add the following two classes. Note, you can paste these all one after the other. But I'll post the full source below anyway.
public class MessageClassA : IMessageInterface
{
    public void WriteMessage(string s)
    {
        Debug.WriteLine($"Message from MessageClassA { s }");
    }
}

public class MessageClassB : IMessageInterface
{

    public void WriteMessage(string s)
    {
        Debug.WriteLine($"Message from MessageClassB { s }");
    }
}
Completing this little project with our Message Logger class :
public class LogMessage
{
    public void WriteMessage(IMessageInterface Message, string v)
    {
        Message.WriteMessage($": Variable is : {v}");
    }
}
To execute this piece of code, you only need a button and paste this inside whichever button you choose. I'm using button 3 :
private void Button3_Click(object sender, EventArgs e)
{
    var bc = new BaseClass();
    bc.ExecuteMe();
}

Upon running the code, you will notice in the Debugger Console area :
Quote:
Message from MessageClassA : Variable is : DefaultValue
Message from MessageClassB : Variable is : foo
Notice how "MessageClassB" does not print the same variable as "MessageClassA" - That is because they are two separate instances, and each one uses whatever parameters set for that object declaration. If you follow OriginalGriff's analogy, its like walking into a car dealer and buying two cars of exactly the same type.

Except when you get home you replace the red leather bucket seats with white leather bucket seats. It's the same thing with the variables of each object, where the cars are your objects, and the seats are only a parameter of the car.

While learning this assignment it is important to understand the difference between Instantiating and statics, and the difference between the two. It's worth nothing, when working with statics. If an object is declared static, you can not instantiate that static class or object.

Using a static object is like declaring a global. Its easier to get and set the values of the class and its static properties without the need to instantiate. Using static classes, methods, and properties makes it easier for the calling code being able to call directly on the object type without the need for instantiating at all.

Further more, these rules are true to an extent, so don't get caught out by not understanding the scope of access modifiers. And on a side note; regarding interfaces, it's also worth noting :
Quote:
An interface declaration may declare zero or more members. The members of an interface must be methods, properties, events, or indexers. An interface cannot contain constants, fields, operators, instance constructors, destructors, or types, nor can an interface contain static members of any kind.

All interface members implicitly have public access. It is a compile-time error for interface member declarations to include any modifiers. In particular, interfaces members cannot be declared with the modifiers abstract, public, protected, internal, private, virtual, override, or static.

If you wish to learn more about Interfaces, you may read Interfaces - C# Programming Guide | Microsoft Docs[^] or ask a new question on that topic.

I hope this helps you to understand instantiating and statics a little better.

Also be sure you understand the scope of your code by reading up on those Access Modifiers - C# Programming Guide | Microsoft Docs[^]

I'm running out of time here, so I will leave this here and I hope this helps you to better understand what to do. :)
 
Share this answer
 
Thank you everyone!

OriginalGriff
your explanation helped me understand the difference between static , non-static and instances.
dnxit 
thanks for your comment i was able to get this to work. At first i had problems but then i worked out that I had to create a constructor with no parameters.
 
Share this answer
 
Comments
Richard Deeming 23-Sep-19 7:59am    
If you want to reply to a solution, click the "Have a Question or Comment?" button under that solution and post a comment.

If you want to reply to a comment, click the "Reply" button next to the comment and reply.

DO NOT post your comment as a "solution" to your question.

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