Reference to a non-shared member requires an object reference
The error message Reference to a non-shared member requires an object reference in VB.NET indicates that you are trying to access a non-shared (instance) member of a class or object without creating an instance of the class first. Non-shared members are specific to instances of the class and cannot be accessed through the class name itself. You need to create an object of the class and use it to access instance members.
How to fix?
To fix this error, you must first create an instance of the class and then call the non-shared member on the instance.
For example, the following code will cause the error:
To fix the error, you must first create an instance of the MyClass class and then call the MyMethod() method on the instance:
You can also avoid this error by using shared members. Shared members can be called without first creating an instance of the class.
For example, the following code will not cause the error:
Here's a detailed explanation with examples:
Non-Shared (Instance) Members
Non-shared members are associated with an instance of a class and are used to store and manipulate data unique to each instance. These members can't be accessed directly through the class itself but require an instance of the class.
Shared (Static) Members
Shared members are associated with the class itself and can be accessed using the class name. They are shared among all instances of the class.
Resolving the Error
To resolve the error, you need to create an object of the class and use it to access non-shared (instance) members. Shared members can be accessed using the class name.
Conclusion
This error typically occurs when you mistakenly attempt to access instance members as if they were shared members or when you forget to create an instance of the class. It's essential to understand the distinction between shared and non-shared members to use them correctly in your VB.NET code.
- Hidden Features of VB.Net
- Check if program is running in VB.Net
- Determine the size of a structure | VB.Net
- How to remove decimal from variable in VB.Net
- VB.Net wait (x) seconds
- How to Get a File Extension Using VB.NET
- VB.NET ToUpper Examples
- Local Variables in VB.Net
- VB.Net - Select Case Statement
- VB.Net DateOnly and TimeOnly
- VB.Net - Get the byte size of type
- Concatenation Operators in VB.Net
- Ternary operator in VB.NET
- Difference between And and AndAlso in VB.Net
- Difference between + and & for joining strings in VB.Net