C# how to access a method inside a object instance?
Hi guys. I am having trouble figuring out how to access a method that exists inside a object instance in C#. How can this be done?
I know that in C++ this can be done using -> but I can not see how to do this in C#.
Assume I have a object called myObject and in that object there is a method called myMethod. How would I externally access myMethod?
Thank you in advance.
int testInt = 51;
//Cls B with Cls A object and initialized
One a1 = new One();
static void Main()
Two Temp = new Two();
int var1 = Temp.a1.testInt; //This part here is not working
Console.ReadLine(); //This stops the program so we can see the result.
Got it :)
My god how missing one thing can mess you up so badly. I forgot to make things public. Thank you and Cheerio!
- UndisclosedLv 53 years ago
In C#, this is determined by the object, not the caller. When creating a function or method within an object, the *Access Modifiers* for the object and its properties/functions/methods apply. In C#, having no access modifier on something defaults it to being "Internal", or only accessible by the same assembly.
Given object MyClass() with the following functions:
public void HuckFinnPaintFence()
private void TomSawyerPaintFence()
internal bool IsFencePainted()
public string NamePersonWhoPainted()
Let's look at the result of calling these:
var x = new MyClass(); // our object
x.TomSawyerPaintFence(); //INVALID, will throw an exception as a *private* function can only be called by another method in the same class.
x.IsFencePainted(); //INVALID if called by a consuming application which isn't part of the same assembly. VALID if called from anything in the same assembly.
x.NamePersonWhoPainted(); //VALID. returns a string.
So a running application might go like this:
And the console output, if the "HuckFinnPaintFence" method is called by the name-fetching function, might return "Tom Sawyer".
- husoskiLv 73 years ago
In both C++ and C#, the syntax for naming a method of a named object uses a dot. So, use myObject.myMethod(), with arguments added between () if needed.
If it's a static method, you use the class name to access it, not an object name.
TheClass.methodName() .... C# syntax
TheClass::methodName() .... C++ syntax
In all cases, the method must be public to be accessible from outside of member functions.