How to call a method directly in C# [duplicate] - c#

This question already has answers here:
C# entry point function
(7 answers)
Closed 2 years ago.
I'm very new to programming, and right now I am learning how to code. Right now I am trying to create some database program, which has some kind of menu, ability to write in data, and read the data which has been already inputed. Somehow I managed to create Menu method, but I don't know, how to open in directly from method Main. Could you please help me, what to do ? I've been looking for simmilar thread, but I can't find anything helpful for me. Again, I am learning from absolute zero, so I hope you won't be very salty about it.
PS: Places where are "Hello World" section I haven't written yet. I got it there only for filing space purposes.
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
public class Program
{
private void Main(string[] args)
{
}
private static bool Menu()
{
Console.Clear();
Console.WriteLine("Vyberte moznost:");
Console.WriteLine("1) Zapis nóveho studenta [N]");
Console.WriteLine("2) Seznam zapsanych studentu [S]");
Console.WriteLine("3) Konec [K]");
Console.Write("\r\nSelect an option: ");
var input = Console.ReadKey();
switch (input.Key)
{
case ConsoleKey.N:
NewStudent();
return true;
case ConsoleKey.S:
StudentSeznam();
return true;
case ConsoleKey.K:
return false;
default:
return true;
}
}
public static void NewStudent()
{
Console.WriteLine("Hello World.");
}
private static void StudentSeznam()
{
Console.WriteLine("Hello World.");
}
}
public class StudentList
{
Console.WriteLine("Hello World.");
}
}

As previously mentiod. Just write Menu() in the main method.
But also, you have a Console.WriteLine directly in your class StudentList. This is not valid.
public class StudentList
{
Console.WriteLine("Hello World.");
}
Put it in a constructor, method or just remove it.
Here is a little info about classes
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes

Your Main method must be static, otherwise the program won't start. Then you can call the Menu() method from Main():
public class Program
{
static void Main(string[] args)
{
Menu();
}

Related

Can I have two entry points in C#

Would it be possible to use two entry points in C# instead of just having the one. For example when I have this:
using System;
namespace learning
{
class cool
{
static void Main(string[] args)
{
}
}
}
Would it be possible to have another entry point such as secondary that the program executes once the main entry point has finished.
You may want to do something like this:
class Program {
public static void EntryPoint1(string[] args) {
// Code
}
public static void EntryPoint2(string[] args) {
// Code
}
public static void Main(string[] args) {
EntryPoint1(args);
EntryPoint2(args);
}
}
Just make sure to not modify args during EnteryPoint1 or if you want to, clone them like this:
class Program {
public static void EntryPoint1(string[] args) {
// Code
}
public static void EntryPoint2(string[] args) {
// Code
}
public static void Main(string[] args) {
EntryPoint1(args.Clone());
EntryPoint2(args.Clone());
}
}
In C#, you specify the entry point using the /main: compiler option.
Imagine that the code containing containing two main() methods as follow :
namespace Application {
class ClassA {
static void main () {
// Code here
}
}
class ClassB {
static void main () {
// Code here
}
}
To use ClassA.main() as your entry point, you would specify the following when compiling:
csc /main:Application.ClassA hello.cs
You can only have a single entry point, but you can write two separate methods, call the first one, and then the second one. You will achieve what you're describing.
using System;
namespace learning
{
class cool
{
static void Main(string[] args)
{
PartOne();
PartTwo();
}
void PartOne() {
// Something happens here
}
void PartTwo() {
// Something else happens here
}
}
}
Additionally (depending on how the program starts up) you can send in arguments to specify which method you want to execute (if you don't need both of them to execute). Then you can just do an "if/else" statement that will decide which method to run depending on the arguments passed into Main

How to make a method accessible from any other classes from the project [duplicate]

This question already has answers here:
Call a method from another class
(5 answers)
Closed 2 years ago.
I have this very basic method that I would like to call often and in many classes.
public void MessageErreur(String message)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
I wanted to know if there was a way to just write it somewhere only once instead of creating a new one for each of my project's classes.
Thanks.
You can create a static helper class:
public static class Helper
{
public static void MessageErreur(String message)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
}
Then use it like
Helper.MessageErreur("text");
P.S. If you are using the newest version of C# and .Net you can try to implement the default interface methods. So the code should look like:
interface IErrorMessager
{
public void MessageErreur(string message)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
}
However, the static helper implementation looks much more natural.
for the static reusable code
public static class SharedMethods
{
public static void SharedReusableMethod1()
{
}
}
// USAGE
private void SomeMethod()
{
SharedMethods.SharedReusableMethod1();
}
For the instance methods same thing , only you need to create instance
public class InstanceMethods
{
public void SharedReusableMethod2()
{
}
}
// USAGE
private void SomeMethod()
{
var c = new InstanceMethods();
c.SharedReusableMethod2();
}
in both cases code is reusable

Attempt to make an "API", why doesn't this work?

I tried to make kind of an API that would ease the creation of new behaviours, inspired on Unity's one.
I'm new to C# and don't why it doesn't work. The test class I made is supposed to write infinitely until program's end what you specified in the ctor, but it doesn't write anything in the console.
Here is what I made :
1 - Program.cs
using System.IO;
namespace Program {
public abstract class Script {
public abstract void Start();
public abstract void Update();
}
class Program {
static bool IsKeyDown(ConsoleKey key) {
if (Console.ReadKey(true).Key == key) return true;
else return false;
}
public static void Main(string[] args) {
Script[] scriptList = {
new Write("Hello World"),
};
foreach (Script s in scriptList) {
s.Start();
}
while (!IsKeyDown(ConsoleKey.Escape)) {
foreach (Script s in scriptList) {
s.Update();
}
}
}
}
}
2 - Write.cs
using System;
namespace Program {
public class Write : Script {
string str;
public Write(string _str) {
str = _str;
}
public override void Start(){}
public override void Update(){
Console.WriteLine(str);
}
}
}
Sorry for bad english I'm french :)
Your code blocks on the Console.ReadKey. If there are no keys available in the input buffer then ReadKey stops and waits for the user to press a key.
You can read this info in the docs where they say
One of the most common uses of the ReadKey() method is to halt program
execution until the user presses a key and the app either terminates
or displays an additional window of information.
You just need to add
static bool IsKeyDown(ConsoleKey key)
{
if (!Console.KeyAvailable) return false;
if (Console.ReadKey(true).Key == key) return true;
else return false;
}

C# Error- Small console app

I'm still trying to get the hang of this. The second part of my Main method will not execute. I believe I've called it correctly. But, obviously I didn't. A little help would be greatly appreciated!
using System;
using static System.Console;
using System.Threading;
namespace mellon_Assignment2
{
class Getting2KnowUapp
{
static void Main()
{
WriteLine("The current time is: " + DateTime.Now);
Thread.Sleep(2000);
AboutMe Me = new AboutMe();
}
}
}
using System;
using static System.Console;
using System.Threading;
namespace mellon_Assignment2
{
class AboutMe
{
public void DisplayInfo()
{
WriteLine("My Name\tAssignment 2");
Thread.Sleep(1500);
WriteLine("ITDEV110\tIntro to Object-oriented Programming");
Thread.Sleep(1500);
WriteLine("Professor\tSeptember 18th");
Thread.Sleep(1500);
}
}
}
You need to call DisplaInfo method. You are only creating the object and doing nothing with it:
AboutMe Me = new AboutMe();
Me.DisplayInfo();
Echoing the other replies, you aren't invoking the method on your class.
If you want it to occur when you create a new instance, you could move it into the constructor.
To do that, change:
public void DisplayInfo()
to
public AboutMe()
public void DisplayInfo() is it's own method and has to be called directly after initialization of the class AboutMe.
If you want the DisplayInfo() method to fire immediately upon initialization of AboutMe then simply add a constructor for AboutMe like so.
class AboutMe {
public AboutMe() {
DisplayInfo();
}
public void DisplayInfo() {
...
}
}
Then you can call:
AboutMe myvariable = new AboutMe();

C# calling a static method

So I'm a java developer new to C# and I can't seem to get this trivial thing working. I have a Tests class which tests a method in another class. For convenience, I made these static so not to rely on any instantiation. For some reason though, my Tests class can't seem to find my Kata class.
namespace Codewars
{
public class Program
{
static void Main(string[] args)
{
}
public static string HoopCount(int n)
{
if (n >= 10)
{
return "Great, now move on to tricks";
}
else
{
return "Keep at it until you get it";
}
}
}
}
Test:
using NUnit.Framework;
namespace Codewars
{
[TestFixture]
class Tests
{
[Test]
public static void FixedTest()
{
Assert.AreEqual("Keep at it until you get it", Kata.HoopCount(6), "Should work for 6");
Assert.AreEqual("Great, now move on to tricks", Kata.HoopCount(22), "Should work for 22");
}
}
}
Your static method is declared inside Program, not Kata, so you should refer to it as Program.HoopCount(someint)

Categories

Resources