question

SharpWindows avatar image
0 Votes"
SharpWindows asked SharpWindows answered

Call a method from a class to another C#

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


dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
2 Votes"
karenpayneoregon answered karenpayneoregon edited

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" }
             };
     }
 }


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Castorix31 avatar image
1 Vote"
Castorix31 answered henrihan-8261 commented

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

the instance of the class

Right, this is the key


1 Vote 1 ·
SharpWindows avatar image
0 Votes"
SharpWindows answered

Thanks @Castorix31 , thanks @karenpayneoregon
now I understood. Thanks for all the examples

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.