Classes in C#
Hello, currently learning C# through the microsoft developer course on youtube. I don't have an intuitive idea of what classes are exactly.
For example if I do
System.Console.WriteLine()
, is System a bunch of System related "classes", and Console is a class which contains different methods related to the console?
So basically like a container? When I look for a definition on google it says a class is a blueprint or a template. In this case is WriteLine a method of an instance of Console?19 Replies
Yes to the second paragraph
couple of things:
System
is a namespace, which is just a container to logically organize related type definitions (like a folder on your filesystem)
Console
is a class, but WriteLine
is a static method which means you don't need an instance of Console
to call itFar as
WriteLine()
goes, that is a static method, which does not need an instancei see that makes sense, so kind of like an associated method in Rust.
so what is an example of an instance of Console?
none, it's a static class so you are not allowed to instantiate it
but in general
myVariable
now contains an instance of MyClass
Static classes are basically containers for methods, since there are no "free" functions in C#
all classes may have static members, but static classes can only have static members (and you can't create instances of them)
Basically a Ruat module which can only contain free functions
ok thanks, slightly got my head around that. And what is the correct name for user defined classes? Like if you made a Car class or Person class? Haven't got round to OOP so maybe will learn about that soon.
just a class
yeah there aren't many intrinsic pieces of C#/.NET, someone wrote the Console class the same way you'd write any of your classes
it's right here https://source.dot.net/#System.Console/System/Console.cs,f907d79481da6ba4
Protip: if you want to check the source code of anything in the docs, they added this nifty cool link not long ago:

thanks, I'll be reading the docs extensively. Another thing I'm not understanding is that I can run a simple hello world program with and without a main function. How does that work?
Like this works:
and also just this:
Console.WriteLine("hello");
also I haven't imported or brought in system into scope yet I can do Console.Writelinetl;dr magic
the second one is "top level statements" and the compiler generates all the stuff in the first one around your code
That's called "top level statements", and how it works is that the compiler generates the class and main method for you
See what the compiler generates
Sharplab is another useful tool for stuff like this
Ctrl + Click on Rider ftw
although I think ReSharper on VS also lets u do that