In Java, we need to have at least a class to hold the main method.
When I create a C# project, the skeleton code looks similar to the Java skeleton codes.
However, should there always be at least one class for the main function in C#?
namespace Hello_World
{
class Hello //Is it compulsory to have this class ?
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadKey();
}
}
}
Edit: I am assuming at least one class is needed in a most basic C# program as the main method needs to be contain within a class. Since main() is needed to run a program, at least one class is needed. Am I right to say that?
No, not necessarily. You can have a struct also. Following is a perfectly valid c# program.
namespace NoClass
{
struct Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world");
}
}
}
Fact that Method should be inside a type in c# you need a enclosing type for your main method. It can be struct or class. It is your choice. but you can't have global funcions in c#.
If you use CS-Script, which is a way to use C# similarly to scripting languages, it's able to execute code without a class.
Granted, that's hardly traditional C#.
Since C# has not a code container/scope that can hold variables and functions - like modules in F# or VB - then yes, you have to define a type (class or struct and not a structural type; which in this scope would be an interface) to hold your code.
In fact you can not have any code out of a class or struct in C# (enum and assembly level attributes does not count!).
Related
I would like to abstract some program logic to a base class for executing a command-line program (functionality similar to what this question was requesting).
in other words, something like this:
public abstract class BaseProgram<T>
{
public static void Main(string[] args)
{
Console.WriteLine(typeof(T));
}
}
public class Program : BaseProgram<string>
{
}
It is important to note that BaseProgram is in a different assembly.
This, however, does not work. The static void Main(string[] args) method must be in the derived class. Can anyone explain why that is? After all, the following is totally 'legal':
Program.Main(null);
BaseProgram<string>.Main(null);
and will output:
> System.String
> System.String
What I would like to know: are there any documented reasons for this outcome?
As was eventually disclosed during the commenting of the other answer, your BaseProgram<T> class is in a different assembly from the one you are trying to execute. The entry point of an assembly has to be in that assembly.
To do otherwise is like giving someone a key and telling them that's the key to your house's front door. Except the key is actually for some other completely different house's front door, so when they show up at your house it does them no good.
If you want to use the BaseProgram<T>'s Main() method, you need to delegate to it. For example, in your own assembly:
static class Program
{
public static int Main(string[] args)
{
return BaseProgram<string>.Main(args);
}
}
Note that for static types or static members of types, there's no need to actually inherit the base type, since you just invoke it via the actual type name instead of an instance reference.
I think the problem is that BaseClass is generic. In order to call main you have to supply a type argument, so which type should the system choose to call this method? Ofcourse it can't make random choices so this is illegal.
I found this in C# 5.0 Language Specification in 3.1 Application Startup
The application entry point method may not be in a generic class declaration.
I’m very new to programming. Actually less than one month back, I couldn’t name even 3 programming languages. So I’m really new to this.
After I understood the class concept and the object concept in OOP in general, I then realised that every single item present in the whole program is either an object or a class ready to give off objects.
Classes are non other than descriptions of objects, which are the main and sole players.
Moreover, functions or method are non other than sort of behavioural manifestation of an existing object.
( I wonder if the code line that we write for a function to be executed, the line of code in itself is a new object that refers to the existing original object that will perform the function we want , as part of its behaviour )
Now, If what I mentioned was near to be correct, What confused me next in my journey to understand OOP as a world wherein every single item is an object being utilised or destroyed, or brought into existence out of a class (blueprint ), which is nothing but a modifiable written description for objects how to be born.
What confused me here is the nature of “system”, “console”, and “namespace” each one of these, is it an object, so that we can call and utilise it without instantiating, or they are special classes readily instantiated as the program runs, or just ordinary classes ( which contradicts everything I understood ), because I can see "system" and "console" called and utilised only, and never instantiated ( just like an object )
Now, namespace seems to be a class that is instantiated into an object in the written script: ( namespace "the application name" { } ) but neither "system" nor "console" seems to be instantiated by programmer!
System is a namespace, Console is a static class inside the namespace System.
Static classes are classes which do not need to be created with the new keyword, and there is only one instance per application (excluding templated static classes - which you don't need to worry about for the moment)
Console can be written like this:
namespace System { //Namespace defined here!
public static class Console { //Static class defined here!
public static void WriteLine() { //Static method defined here!
//Implementation goes here
}
}
}
Note the keyword static when declaring the class. Removing this keyword would turn it into a normal class, and you'd have to use it like this:
var console = new System.Console();
console.WriteLine();
Based on the comments from Bauss and Physician about static methods.
You can write this, as well:
public class MyClass
{
public static void DoSomethingStatically()
{
}
public void DoSomethingNormally()
{
}
}
Now, you can do this:
MyClass.DoSomethingStatically();
but you cannot do:
MyClass.DoSomethingNormally();
To use the second method, you must create an instance:
var myClass = new MyClass();
myClass.DoSomethingNormally();
Note:
You cannot call a static method on an instance, so it is invalid to do the following:
var myClass = new MyClass();
myClass.DoSomethingStatically();
You can think of namespaces as containers of classes. System is a namespace which contains the Console class. Console is a special kind of class called a static class. A static class is denoted by the static keyword. The Console class's declaration would look something like this:
namespace System {
public static class Console {
//lots of stuff...
}
}
Actually you can read the Console class's source code in http://referencesource.microsoft.com
A static class cannot be instantiated. It just does its own work. It doesn't have objects. One of reasons is that it doesn't make sense to have objects. For example, the Math class is a static class because it doesn't make sense to say "Let's create a Math object!". Because Math is not like Cows or Streams or BinaryFormatters, which all are non static classes Generally, anything that you can prefix with "a" is not static. "a Stream", "a BinaryFormatter" etc.
Now for the namespace concept. You know sometimes the same word may mean different stuff depending on the context. e.g. Stream, in a programming context it means a file stream or some other kind of streams. But in a casual conversation, you say stream to mean a stream of water or something like that. So now you have to create two stream classes but there's a name conflict! That's why we have namespaces. Let's look at a real example. There are at least 2 classes called Path, but they are in different namespaces so it's ok to have the same name. One is in the System.Drawing namespace and the other is in the System.IO namespace. We often refer to those two classes as "System.IO.Path" and "System.Drawing.Path". Or you can write using directives.
Conclusion:
Both System and Console are not objects. They are a namespace and a static class respectively. And the word namespace denotes a namespace so it's not an object either.
Let's say I have an enum named ExitCodes. I also want to have a method called ErrorCodes.Quit. In C++, you can put methods under namespace, while in C# you can't. So, you can have both the enum and the method under the namespace ExitCodes in C++, but in C# you're limited. I wanted to ask two questions about those differences.
Is there a workaround for this in C#? Can I achieve the same, somehow? I know I could make the class non-static, make the constructor private and then insanitate static instances of ExitCodes with values and a static method Quit, but that's too much work.
I want to be able to make custom types like it is in C++. For example, in C++ I can do:
using exit_code_t = int;
I doubt it's possible in C#, but why not ask here.
Is there a workaround for this in C#?
Yes, put the method (and the Enum if you want) in a class instead of a namespace. Syntactically it will look the same:
public class ExitCodes
{
public enum ExitCodes
{
...
}
public static void Quit()
{
...
}
}
Now you can use ExitCodes.ExitCodes and ExitCodes.Quit();
I want to be able to make custom types like it is in C++
In C++ that just gives an alias to the int type. You can do the same thing in C#, but you have to use the actual type name, not the int keyword:
using System;
using MyInt = System.Int32;
public class Test
{
public static void Main()
{
// your code goes here
Console.WriteLine(typeof(MyInt).ToString()); // will print System.Int32
}
}
One difference in C# is that the alias only applies to the current file. So it not exactly the same as the C++ alias/typedef but it's as close as you're going to get.
Sorry for the unlearned nature of this question. If there's a simple answer, just a link to an explanation will make me more than happy.
After 6 months programming I find static classes to be somewhat useful for storing routines that apply to many different classes. Here's a simplified example of how I use static classes, it's a class for parsing text into various things
public static class TextProcessor
{
public static string[] GetWords(string sentence)
{
return sentence.Split(' ');
}
public static int CountLetters(string sentence)
{
return sentence.Length;
}
public static int CountWords(string sentence)
{
return GetWords(sentence).Length;
}
}
And I use this in obvious ways like
class Program
{
static void Main(string[] args)
{
string mysentence = "hello there stackoverflow.";
Console.WriteLine("mysentence has {0} words in it, fascinating huh??", TextProcessor.CountWords(mysentence));
Console.ReadLine();
}
}
My question is: Why is it necessary to wrap these static methods in a static class?
It seems to serve no purpose. Is there a way I can have these methods on their own not wrapped in a class? I know encapsulation is beneficial but I don't see the use for static methods wrapped in static class. Is there something I am missing stylistically or otherwise? Am I completely barking up a silly tree? Am I thinking too much?
In C#, any method has to be declared inside a class. That's just how the language is specified.
A static class is actually more akin to a module than a class, so I too think you should be able to either:
define a function outside a class or;
import a module the same way you import a namespace (with using)
VB.NET, F# and Nemerle actually allow you to declare modules and import them; what allows you to use their methods unqualified.
This is valid Nemerle:
using System.Console; // import static methods in the Console class
class Hello {
static Main() : void {
WriteLine("Hello, world!"); // unqualified access!
}
}
Also, take a look at extension methods, they might allow you to "solve" this in a different way. The methods in your TextProcessor are begging to be string extension methods.
This post by eric lippert gives a pretty detailed explanation. I'm not sure if this guy "eric" knows what he's talking about or not though ;-)
It would be somewhat awkward to have methods just dangling around in a random namespace.
I suspect the answer is to provide "scope". Just because a method is static, doesn't mean it doesn't have a scope. It can still access other static private methods or member variables - and the class provides a "home" for these things to live in.
Static classes can also have static constructors that get called the first time a static method is used, so this provides the ability to set stuff up as needed.
It's more of an organizational design than anything to due with technical limitations.
A static method is a method called in a single instance of a class that is created at run-time.
I'm new to c# and I was wondering if someone could tell me how to create a global module for changing a form like you would do in vb, and then how to call that module.
Thanks
Update:
Ok so i have multiple forms and instead of writing the same 2 lines over and over, which are..
Form x = new Form1();
x.Show();
Is it possible to add this to a class to make it easier. How do i do it? never made a class before. got the class up but unsure how to write the code.
There is nothing as Global Module in C# instead you can create a Public class with Static Members like:
Example:
//In a class file
namespace Global.Functions //Or whatever you call it
{
public class Numbers
{
private Numbers() {} // Private ctor for class with all static methods.
public static int MyFunction()
{
return 22;
}
}
}
//Use it in Other class
using Global.Functions
int Age = Numbers.MyFunction();
No, this requires help from a compiler. A VB.NET module gets translated to a class under the hood. Which is very similar to a static class in C#, another construct that doesn't have a real representation in the CLR. Only a compiler could then pretend that the members of such a class belong in the global namespace. This is otherwise a compat feature of the VB.NET compiler, modules were a big deal in the early versions of visual basic.
A static class declared without a namespace is the closest you'll get in C#. Util.Foo(), something like that.
The answer with public class using static MethodName is close. You could take it a step further and make the class static too.
Here is another Stack Overflow answer that talks about it. Classes vs. Modules in VB.Net