Earlier I was putting some code together for an example. I got the following error (Top-level statements must precede namespace and type declarations):
Error CS8803 Top-level statements must precede namespace and type declarations. ConsoleApp2 C:UserspetersourcereposConsoleApp2ConsoleApp2Program.cs 25
The code looked like the following:
public static class StringExtensions
{
public static string ToCommaSeperatedString(this IEnumerable<string> list)
{
return string.Join(",", list);
}
}
var someList = new List<string>
{
"A","B","C"
};
Console.WriteLine(someList.ToCommaSeperatedString());
In the above we declare a new type of class (StringExtensions) and then we create a list of strings, however with Top-level statements (TLS) you must declare your namespaces and types — for example classes — first. There are two solution to this, the code can be rearranged so that the class is defined last:
var someList = new List<string>
{
"A","B","C"
};
Console.WriteLine(someList.ToCommaSeperatedString());
public static class StringExtentions
{
public static string ToCommaSeperatedString(this IEnumerable<string> list)
{
return string.Join(",", list);
}
}
Alternatively we can go back to the old way of making entry points with a static void Main
method:
class Program
{
static void Main(string[] args)
{
var someList = new List<string>
{
"A","B","C"
};
Console.WriteLine(someList.ToCommaSeperatedString());
}
}
public static class StringExtentions
{
public static string ToCommaSeperatedString(this IEnumerable<string> list)
{
return string.Join(",", list);
}
}
I hope you found this helpful, please leave a comment down below if you did!
C# 9.0 introduced top-level statements that allow you to skip all the boilerplate code and get to the point quickly. No need to declare a namespace, class, or even a Main()
method. Just open your editor and start writing beautiful C# code.
Writing a simple console program in C# has always involved a ton of ceremony. You have to create a class named Program. Then declare the Main
method that is public
, static
, void
, and takes an array of strings as arguments. Here is an example.
using System;
class Program
{
static void Main(string[] args)
{
int sum = 45 + 50;
Console.WriteLine(sum);
}
}
Enter fullscreen mode
Exit fullscreen mode
In the above example, there is too much clutter. There are only two lines that are actually doing something. When a beginner reads the above program, it can feel quite overwhelming.
- What is System? Why are we using it?
- What is a class? Where are the students?
- What is static, why is it void?
- What is args?
The essential part in the above program is the code that adds and displays the sum of two numbers. Rest is just ceremony.
In C# 9.0, you can simply write this:
int sum = 45 + 50;
System.Console.WriteLine(sum);
Enter fullscreen mode
Exit fullscreen mode
Using sharplab, we can see how the C# compiler transforms this code before it’s compiled. Notice that the Program
class and Main
method are still getting generated behind the scenes, but you don’t have to write them.
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
[CompilerGenerated]
internal static class <Program>$
{
private static void <Main>$(string[] args)
{
int value = 95;
Console.WriteLine(value);
}
}
Enter fullscreen mode
Exit fullscreen mode
What happens to the command-line arguments?
They are still accessible using the args
array. You can run the following code using dotnet run hello
, and it will print hello to the console.
System.Console.WriteLine(args[0]);
Enter fullscreen mode
Exit fullscreen mode
How can I return a status code?
Just return it, as you normally would. For example,
System.Console.WriteLine("Hello");
return 0;
Enter fullscreen mode
Exit fullscreen mode
Can I have multiple files with top-level statements?
No. Only one file in your application can use top-level statements. The compiler throws an error when it finds multiple files containing top-level statements.
Can I create classes in the same file?
Yes, the only requirement is that the top-level statements should come before any type declaration. For example,
using System;
var animal = new Animal { Name = "Dog" };
Console.WriteLine(animal.Name);
class Animal
{
public string Name { get; set; }
}
Enter fullscreen mode
Exit fullscreen mode
You can’t create a class and then write your statements. For example, this code is invalid.
using System;
class Animal
{
public string Name { get; set; }
}
var animal = new Animal { Name = "Dog" };
Console.WriteLine(animal.Name);
Enter fullscreen mode
Exit fullscreen mode
It throws the following error.
error CS8803: Top-level statements must precede namespace and type declarations.
Enter fullscreen mode
Exit fullscreen mode
Top-level statements make C# beginner-friendly, giving it a scripty feel, like Ruby or Python. They also make simple programs clear and expressive. If you just want to understand a concept in C# or try out a base class library, you can quickly do so using the top-level statements. They are also great for small tools and utilities.
Did I miss anything? Let me know.
Timeless DEV post…
How to write a kickass README
Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.
If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.
Read next
Generate sequence numbers in Cosmos DB
Tatsuro Shibamura — Jan 15
Debugging in .NET apps using Visual Studio Part 1
Hootan Hemmati — Jan 13
EF Power Tools tutorial
Karen Payne — Jan 13
Dotnet, C#, code format on JetBrain IDE Rider
TSOTSI1 — Jan 13
Once unpublished, all posts by software_writer will become hidden and only accessible to themselves.
If software_writer is not suspended, they can still re-publish their posts from their dashboard.
Note:
Once unpublished, this post will become invisible to the public and only accessible to Akshay Khot.
They can still re-publish the post if they are not suspended.
Thanks for keeping DEV Community 👩💻👨💻 safe. Here is what you can do to flag software_writer:
Make all posts by software_writer less visible
software_writer consistently posts content that violates DEV Community 👩💻👨💻’s
code of conduct because it is harassing, offensive or spammy.
I was following { this tutorial } on how to make a pong game, I basically wrote the code word-to-word from the site, but it doesnt work for some reason. here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour {
public KeyCode moveUp = KeyCode.W;
public KeyCode moveDown = KeyCode.S;
public float speed = 10.0f;
public float boundY = 2.25f;
private RigidBody2D rb2d;
}
{
// Start is called before the first frame update
void Start() {
rb2d = GetComponent<RigidBody2D>();
}
// Update is called once per frame
void Update() {
var vel = rb2d.velocity;
if (Input.GetKey(moveUp)) {
vel.y = speed;
}
else if (Input.GetKey(moveDown)) {
vel.y = -speed;
}
else {
vel.y = 0;
}
rb2d.velocity = vel;
var pos = transform.position;
if (pos.y > boundY) {
pos.y = boundY;
}
else if (pos.y < -boundY) {
pos.y = -boundY;
}
transform.position = pos;
}
}
I belive it is something to do with this:
public class PlayerControls : MonoBehaviour {
public KeyCode moveUp = KeyCode.W;
public KeyCode moveDown = KeyCode.S;
public float speed = 10.0f;
public float boundY = 2.25f;
private RigidBody2D rb2d;
}
But I am not sure how to fix it since the site doesnt specify where I need to put it.