Why use static methods in program.cs C#? [duplicate] - c#

This question already has answers here:
When to use static methods
(24 answers)
Closed 2 years ago.
I always knew that I have to use static methods but I wonder why?
As you can see below I have to make "MigrateDatabase" Static
using System;
namespace OdeToFood
{
public class Program
{
public static void Main(string[] args)
{
MigrateDatabase();
}
private static void MigrateDatabase()
{
//.....
}
}
}

Let's just be clear, the only reason MigrateDatabase has to be static in this case is because you're calling it from a static method (Main). If instead MigrateDatabase was an instance method on a class, you could instantiate that class and call it
using System;
namespace OdeToFood
{
public class Program
{
public static void Main(string[] args)
{
var migration = new Migration();
migration.MigrateDatabase();
}
}
public class Migration
{
private void MigrateDatabase()
{
//.....
}
}
}
You could also put it as a instance method on Program if you're instantiating an instance of that class
using System;
namespace OdeToFood
{
public class Program
{
public static void Main(string[] args)
{
var program = new Program();
program.MigrateDatabase();
}
private void MigrateDatabase()
{
//.....
}
}
}

Related

Execute code from string in net core runtime?

For example we have such a class:
namespace ConsoleApp1
{
public class Program
{
public int x = 0;
public int y = 1;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Program program = new Program();
program.RunScript(Console.ReadLine());
}
public void RunScript(string script)
{
//....
}
public void CallMethod1()
{
}
public void CallMethod2()
{
}
}
}
And in the console I want to enter an expression for execution, in the language C#:
"if(x > y){CallMethod1();}else{CallMethod2();}"
how can this expression be executed? I've seen examples with Roslyn https://learn.microsoft.com/en-us/archive/msdn-magazine/2017/may/net-core-cross-platform-code-generation-with-roslyn-and-net-core
but they call static functions or functions from the new namespace, but I need to call a function that is already in the current namespace

How to call a class rather than a method inside a class?

so I want to make it easy to call Console.WriteLine() (from the namespace system) so I wrote:
using System;
namespace main
{
namespace easier
{
public class print
{
public print(string input)
{
Console.WriteLine(input);
}
}
}
}
But when I try to call print("Hello World); it says CS1955: Non-invocable member 'print' cannot be used like a method.
Is there a way so I don't have to do class.print("Hello World"); just print("Hello World");?
Thanks in advance!
You can use using static
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-static
using System;
using static Easier;
class Program
{
static void Main(string[] args)
{
Print("message");
}
}
public static class Easier
{
public static void Print(string value)
{
Console.WriteLine(value);
}
}

Alias for static member in C#?

I have a static member:
namespace MyLibrary
{
public static class MyClass
{
public static string MyMember;
}
}
which I want to access like this:
using MyLibrary;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
MyMember = "Some value.";
}
}
}
How do make MyMember accessible (without MyClass.) to MyApp just by adding using MyLibrary?
C# doesn't allow you to create aliases of members, only of types. So the only way to do something like that in C# would be to create a new property which is accessible from that scope:
class Program
{
static string MyMember
{
get { return MyClass.MyMember; }
set { MyClass.MyMember = value; }
}
static void Main(string[] args)
{
MyMember = "Some value.";
}
}
It's not really an alias, but it accomplishes the syntax you're looking for.
Of course, if you're only accessing / modifying a member on MyClass, and not assigning to it, this can be simplified a bit:
class Program
{
static List<string> MyList = MyClass.MyList;
static void Main(string[] args)
{
MyList.Add("Some value.");
}
}

Problem when with generic delegates in C#

I have a sample program where I have a class called ObserverTest where I have two methods
one for subscription and one for notify for any type T but I get some build errors.
Following is my sample code>
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ObserverTest obs = ObserverTest.Instance();
obs.SubscribeToChange<int>(GotChange);
obs.NotifyChange<int>(200);
Console.ReadLine();
}
private static void GotChange(int val)
{
Console.WriteLine(string.Format("Changed value is {0}", val));
}
}
public class ObserverTest
{
private static ObserverTest _obsTest;
private Action<T> _observer;
private ObserverTest()
{
}
public static ObserverTest Instance()
{
return _obsTest = _obsTest == null ? new ObserverTest() : _obsTest;
}
public void NotifyChange<T>(T val)
{
_observer(val);
}
public void SubscribeToChange<T>(Action<T> observer)
{
_observer = observer;
}
}
}
and followings are the errors:
Error 1 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Administrator\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 24 22 ConsoleApplication1
Error 2 The field 'ConsoleApplication1.ObserverTest._observer' cannot be used with type arguments C:\Users\Administrator\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 37 10 ConsoleApplication1
Can anyone please help me in removing the errors ?
Thanks in advance.
Try to add generic in the class definition:
public class ObserverTest<T>
complete code:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ObserverTest<int> obs = ObserverTest<int>.Instance();
obs.SubscribeToChange<int>(GotChange);
obs.NotifyChange<int>(200);
Console.ReadLine();
}
private static void GotChange(int val)
{
Console.WriteLine(string.Format("Changed value is {0}", val));
}
}
public class ObserverTest<T>
{
private static ObserverTest<T> _obsTest;
private Action<T> _observer;
private ObserverTest()
{
}
public static ObserverTest<T> Instance()
{
return _obsTest = _obsTest == null ? new ObserverTest<T>() : _obsTest;
}
public void NotifyChange<E>(T val)
{
_observer(val);
}
public void SubscribeToChange<E>(Action<T> observer)
{
_observer = observer;
}
}
}
If you have a member that's a generic, like _observer, you need to put a type argument on the ObserverTest class, like so:
public class ObserverTest<T> {
}
Of course, you'll need to modify your Instance method as well.
The problem you are having is that you are declaring a field member that has a generic type and the class does not:
public class ObserverTest
{
private static ObserverTest _obsTest;
private Action<T> _observer;
...
}
So when you try to create an instance of the ObserverTest class, it tries to setup the field members and runs into the problem of not knowing what concrete type _observer is.
To fix this you'll have to define the class with a generic parameter and any calls that instantiate the class:
public class ObserverTest<T>
{
private static ObserverTest _obsTest;
private Action<T> _observer;
public static ObserverTest<T> Instance<T>()
{
...
}
...
}

Clean code which version is correct?

When the only code in there is for a class how would you code it adding public to the default class like so
namespace HW2_2_Spaceship
{
public class Spaceship //added public to the default class
{
static void Main(string[] args)
{
}
or
namespace HW2_1_Book
{
class Book
{
static void Main(string[] args)
{
}
public class Book // added a new class with in the default class
{
In general, each class should have their own file.
Main should be in Program.cs
There are usecases where you can use Inner classes, see Using Inner classes in C#.
//Program.cs, if u use visual studio then ensure you add
// the public access modifier yourself
namespace HW2_2_Spaceship
{
public class Program
{
public static void Main(string[] args)
{
//Do something here
}
}
}
//Book.cs, add the public modifier to the class
namespace HW2_2_Spaceship
{
public class Book
{
//add method and properties here
}
}

Categories

Resources