Home > Mobile >  How to call a method inside another method's object (list)? C#
How to call a method inside another method's object (list)? C#

Time:09-26

I am trying to figure out how this is possible (if it is at all). Code looks basically like this:

public class MyClass
{
    public Method1()
    {
        List<string> mylist = new List<string>();
        mylist.  /*how can I call Method2?*/
    }

    public Method2()
    {
        /*automation code for changing sequence of the UI objects
        (action)*/
    }
}

I am able to use built-in methods like Sort(), Add() all of them after

using namespace System;
using namespace System.Collections;
using namespace System.Collections.Generic;

and so on, but I was wondering if I have to put Method2() inside another class, import it as a namespace and then use it on the object mylist inside Method1().

CodePudding user response:

You'd do it the opposite way around: instead of trying to give the object a new method, you give the method the object:

public class MyClass
{
    public void Method1()
    {
        List<string> mylist = new List<string>();
        Method2(mylist); /*how can I call Method2?*/
    }

    public void Method2(List<string> list)
    {
        //does something with list      
    }
}

Technically there's also the possibility of extension methods. But you really want to understand why Microsoft made extension methods and what they are good for. You don't just spam extension methods, just because it's technically possible.

Trust me, when you type mylist. you really want to see only Microsoft methods, because Microsoft provided the List<T> class. You don't want to see thousands of methods everyone thought could be useful.

CodePudding user response:

public class MyClass
{
    public void  Method1()
    {
        List<string> mylist = new List<string>();

        /*how can I call Method2?*/
        Method2(mylist);
    }

    public void Method2(List<string> mylist)
    {
        //does something with my list
    }
}
  • Related