Call a method from a class to another C#

swodniW 141 Reputation points
2021-04-03T10:10:53.223+00:00

Hello C#
I am learning C# but i don't understand how to call a method from a class to another

example
class A
{
void Caller()
{
B.Called(); //CS0120 error
}
}
class B
{
void Called()
{
//do something
}
}

How to call Called() from A?
Thanks in advice

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,036 Reputation points
    2021-04-03T10:41:47.133+00:00

    Hello,

    See Access Modifiers (C# Programming Guide)

    Then in a Console project, in this case .NET Core experiment with the following.

    • First example has a mixture of public and private modifiers
    • First example uses static which means we don't have to initialize the class which is only good when no initialization is needed which the second class shows.

      Console project

      using System;  
      
      namespace ConsoleApp1  
      {  
          class Program  
          {  
              static void Main(string[] args)  
              {  
                  Operations.Hello();  
                  Operations.Active = true;  
      
                  AnotherClass instance = new ();  
                  instance.Hello();  
      
              }  
          }  
      
          public class Operations  
          {  
              public static bool Active { get; set; }  
              public bool Active1 { get; set; }  
              private bool Active2 { get; set; }  
              public static void Hello()  
              {  
      
              }  
      
              private static void Hello1()  
              {  
      
              }  
          }  
      
          public class AnotherClass  
          {  
              public void Hello()  
              {  
              }  
      
              private void World()  
              {  
      
              }  
          }  
      }  
      

    Console project 2

    Here a singleton is used which means you can call this class anyplace in the same namespace and information is retained

    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.Linq;  
    
    namespace ConsoleApp1  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                var fileName = ApplicationSettings.Instance.ProductsFileName;  
                Console.WriteLine($"Reading from: {fileName} ");  
    
                foreach (var line in ApplicationSettings.Instance.ReadProducts())  
                {  
                    // TODOL  
                }  
    
                ApplicationSettings.Instance.Person.FirstName = "Karen";  
                ApplicationSettings.Instance.Person.LastName = "Payne";  
    
                Demo();  
    
                Console.ReadLine();  
            }  
    
            static void Demo()  
            {  
                Console.WriteLine(ApplicationSettings.Instance.Person);  
            }  
        }  
    
        public sealed class ApplicationSettings  
        {  
            /// <summary>  
            /// Creates a thread safe instance of this class  
            /// </summary>  
            private static readonly Lazy<ApplicationSettings> Lazy = new(() => new ApplicationSettings());  
            /// <summary>  
            /// Access point to methods and properties  
            /// </summary>  
            public static ApplicationSettings Instance => Lazy.Value;  
            public string ProductsFileName => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFiles", "Products.txt");  
    
            public List<string> ReadProducts() => File.ReadAllLines(ProductsFileName).ToList();  
            public Person Person { get; set; }  
    
            private ApplicationSettings()  
            {  
                Person = new Person();  
    
            }  
        }  
    
        public class Person  
        {  
            public string FirstName { get; set; }  
            public string LastName { get; set; }  
            public override string ToString() => $"{FirstName} {LastName}";  
    
        }  
    }  
    

    Console 3

    Here is scoping a local method

    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.Linq;  
    
    namespace ConsoleApp1  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                var fileName = ApplicationSettings.Instance.ProductsFileName;  
                Console.WriteLine($"Reading from: {fileName} ");  
    
                foreach (var line in ApplicationSettings.Instance.ReadProducts())  
                {  
                    // TODO  
                }  
    
                Console.ReadLine();  
            }  
        }  
    
        public sealed class ApplicationSettings  
        {  
            /// <summary>  
            /// Creates a thread safe instance of this class  
            /// </summary>  
            private static readonly Lazy<ApplicationSettings> Lazy = new(() => new ApplicationSettings());  
            /// <summary>  
            /// Access point to methods and properties  
            /// </summary>  
            public static ApplicationSettings Instance => Lazy.Value;  
            public string ProductsFileName => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFiles", "Products.txt");  
    
            public List<string> ReadProducts()  
            {  
    
                /*  
                 * This method is callable only in ReadProducts()  
                 */  
                string MakeUppercase(string sender) => sender.ToUpper();  
    
                var lines = File.ReadAllLines(ProductsFileName).ToList();  
    
                for (int index = 0; index < lines.Count; index++)  
                {  
                    lines[index] = MakeUppercase(lines[index]);  
                }  
    
                return lines;  
            }  
    
    
        }  
    
    
    }  
    

    Create record types

    See the docs

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    
    namespace WithExpressionsApp  
    {  
    #nullable enable  
    
    
        class Program  
        {  
            static void Main(string[] args)  
            {  
    
                var person = Mocked.People().FirstOrDefault(peep => peep.FirstName == "Karen");  
    
    
                WriteSectionBold("Founded", false);  
    
                WriteIndented(person?.ToString());  
    
                EmptyLine();  
    
    
                if (person is not null)  
                {  
                    var otherPerson = person with { LastName = "Black" };  
    
                    WriteSectionBold("using with",false);  
    
                    WriteIndented(otherPerson.ToString());  
                }  
    
                Console.ReadLine();  
            }  
        }  
    
        public record Person  
        {  
            public string? FirstName { get; init; }  
            public string? LastName { get; init; }  
            public override string ToString()  
            {  
                return $"{FirstName} {LastName}";  
            }  
        }  
    
        class Mocked  
        {  
            public static List<Person> People()  
            {  
                List<Person> peopleList = new();  
    
                peopleList.Add(new Person() { FirstName = "Bob", LastName = "Jones"});  
                peopleList.Add(new Person() { FirstName = "Karen", LastName = "Smith"});  
    
                return peopleList;  
    
            }  
    
        }  
        class Mocked1  
        {  
            public static List<Person> People() =>  
                new()  
                {  
                    new() {FirstName = "Bob", LastName = "Jones"},   
                    new() {FirstName = "Karen", LastName = "Smith"}  
                };  
        }  
        class Mocked3  
        {  
            public static List<Person> People() =>  
                new List<Person>()  
                {  
                    new Person() { FirstName = "Bob", LastName = "Jones" },  
                    new Person() { FirstName = "Karen", LastName = "Smith" }  
                };  
        }  
    }  
    
    2 people found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Castorix31 81,726 Reputation points
    2021-04-03T10:31:46.537+00:00

    See for example the part at Call method in C#

    "
    You can also use the instance of the class to call the public methods of other classes from another class.
    For example, the method FindMax belongs to the NumberManipulator class, and you can call it from another class Test.

    using System;
    namespace CalculatorApplication
    {
        class NumberManipulator
        {
            public int FindMax(int num1, int num2)
            {
                /* Local variable declaration */
                int result;
    
                if (num1 > num2)
                    result = num1;
                else
                    result = num2;
    
                return result;
            }
        }
        class Test
        {
            static void Main(string[] args)
            {
                /* Local variable definition */
                int a = 100;
                int b = 200;
                int ret;
                NumberManipulator n = new NumberManipulator();
                //Call the FindMax method
                ret = n.FindMax(a, b);
                Console.WriteLine("The maximum value is: {0}", ret );
                Console.ReadLine();
    
            }
        }
    }
    

    "

    1 person found this answer helpful.

  2. swodniW 141 Reputation points
    2021-04-03T13:59:41.19+00:00

    Thanks @Castorix31 , thanks @Karen Payne MVP
    now I understood. Thanks for all the examples

    0 comments No comments