Are System, console, Namespace classes or already instances? - c#

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.

Related

C# in Unity 3D/2D: Am I required to use Classes for every script?

A little background: I'm new to C# and Unity, but catching on very quickly. I'm also hoping this thread will not spark a debate about the merits of classes and abstract coding, as that debate is unrelated and well-worn (and unnecessarily heated); so please keep that in mind.
I'm simply wondering if every C# script in Unity is required to have a main class in any way or for any reason.
Or instead, can methods, and variables can be written outside of a class in a blank file (with namespaces) to be used in a video game?
I'm asking because, when I create a new C# script, it seems to force a class into my file and I'm afraid of breaking things.
I hope to keep code abstraction to a minimum, and the current project
I'm working on has several situations where a class is not needed, or
only one instance of the class will be used. I'd like to simply avoid
using classes in those cases.
In terms of declaring/defining variables and methods outside of any class, you can't really do that in C#. It just isn't how the language was designed (the answers to the question I linked to expand on that idea, so I won't duplicate them here).
You're not without options, though; if you have a number of variables or methods that need to be accessible from different places and don't need an object reference, you can make them static, so you won't need to instantiate the class to make use of them:
public class UtilityClass
{
public static float GravityConstant = 3.51f;
public static string GameName = "MyFirstGame";
public static float CalculateProduct(float a, float b)
{
return a * b;
}
}
Then, you can reference the class's methods/members by accessing it through its name:
float product = UtilityClass.CalculateProduct(6, 1.5f);
An example of where you might use this pattern is when defining mathematical formulae which aren't included in Unity's Mathf methods, and using them in multiple classes.
Additional note: Creating a new C# script through Unity's editor UI will default to declaring a class of the same name that inherits from Monobehaviour. You can alter it to remove the inheritance from Monobehaviour if you don't need any of the methods/attributes of the class, which avoids unnecessary overhead. One example for this would be with a static class that you never need to instantiate.
Yes, you are.
In C#, things like global variables and functions just do not exist. Everything must be contained in a class.
"But what should I do in order to declare some stuff that can be accessed everywhere, without creating an object?" you asked. There is something called the static modifier. You can access the methods or variables or fields or properties marked with this modifier without creating an object of that class.
You just add the word static in a method and it becomes a static method! How simple!
Let's see an example.
I have this non-static method:
public class MyClass {
public void DoStuff () {
}
}
I can call it like this:
var obj = new MyClass();
obj.DoStuff();
But if I modify it with static,
public class MyClass {
public static void DoStuff () {
}
}
I can call it like this:
MyClass.DoStuff();
How convenient!
Note:
Please do not misuse the static modifier! Only use it when it makes sense! When? When the method is a utility method or when the method does not belong to individual objects but the class itself.
First of All you need to check where Methods define as offical
docs stated
"Methods are declared in a class or struct by specifying the access
level such as public or private...."
So, Method should be declare in a Class or struct and A given class
should be, ideally, responsible for just one task.(see also)
Your this question "Or instead, can methods, and variables can be
written outside of a class in a blank file (with namespaces) to be
used in a video game?" answer is hidden in the below question.
Can there be stand alone functions in C# without a Class?
No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.
You have to make a class in order to use methods or its variable
either instance class or static class.
Am I required to use Classes for every script? Every script means you required a class. Unity Support Component Based
Architectural Design and if you require any script related
work then you definitely require a script component which means a
class require.
Finally for singleton, thanks to Unity3dWiki great detail
available. I think you will be feel comfortable to code and writing
class if you keep in mind component based architecture of Unity3d.
Singleton vs Static: I will also recommend to check this: Why do you use a Singleton class
if a Static class serves the purpose
Hope it will help.
[Note: If this helpful Any one can update this answer for future reference and use].

Any design patterns for initialization? C#

I have a class called initialize that runs at the beginning of my program. Originally I explicitly hard coded all the classes that it was supposed to instantiate but I would like to make it more generic and remove the hard coded classes so I can mark the class closed for modification.
My first thought was to create a queue of Types that my initialize class would cycle through and instantiate all the Types that are in the queue.
I then wanted to decide on a per class basis if it should be added to the queue or not. By adding itself to the queue from within the class. The problem is that I cant add a class to the queue unless it is already been instantiated. I know that variables can be initialized before running but obviously not methods. So Im stuck on figuring out weather what I would like to do is possible on not.
Something along the Lines of:
MyClass
{
initalize.instance.Enqueue(typeof(MyClass));
}
I meant something along these lines.
public static class Initializer
{
public static void Initialize()
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
foreach (var type in assembly.GetTypes())
if (type.IsDefined(typeof(InitializeAttribute), true))
Console.WriteLine("Need to initialize {0}", type.FullName);
}
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class InitializeAttribute : Attribute
{
}
[Initialize]
public sealed class ToBeInitialized
{
}
The pattern that you're looking for, if I understand your question correctly, is the factory method pattern. Take a look at this link: http://en.wikipedia.org/wiki/Factory_method_pattern#C.23
If you're initializing class static state then this isn't necessary. Just add a static constructor to all of your types and the .NET runtime will lazily call the static constructor before any static members of that class are accessed (be it a field, method, property or event). This can also work for the singleton pattern - however as I said, static constructors are JIT-evaluated which can introduce non-deterministic delays in your program.
The alternative is to use reflection to iterate through each Type in the assembly and perform your own initialization. This is how plugin systems work.

C#, Classes inside Original Class bad programming practice?

I have been following a workshop whilst I'm learning C#.
One of the class exercises that was given was to create a program that prints your name out into the console.
I have developed this.
My questions is .. is putting other classes into the main class a bad programming practice? I figure I'd ask before I started making habits! Should I just create a seperate class, incase I want to expand it to an actual project?
class Exercise1
{
static void Main()
{
Character myCharacter = new Character();
myCharacter.name = "tekaC";
Console.WriteLine("Hello {0}!", myCharacter.name); //Prints the character's name into the Console output
}
}
class Character
{
public string name;
}
It's not clear whether you mean:
Nesting one class within another
Keeping two top-level classes within the same source file
The latter is almost always a bad idea - class Foo should almost always be declared in Foo.cs so that it's easy to find. There are exceptions to this - for example, in Noda Time I have several delegates declared in a single file called Delegates.cs, but that's a special case - there's no code involved, and once you know that if you want to find any delegate, you look in Delegates.cs, it's fine.
Nested classes are fine when used appropriately - but I would default to creating new top-level classes. I rarely use nested classes unless they're meant to be implementation details which only the containing class is interested in. I usually make them private for exactly that reason - none of the rest of the code in the project needs to know about them at all.
One other point about your current code: you've got a public field, which is generally poor encapsulation. You should use a property instead, so that you can hide the implementation details. You probably want to give the Character class a constructor which takes the name at construction time too - you could then potentially make the underlying field readonly. For example:
// You may not want it to be internal, and you may not want it to be sealed -
// but you should think about both decisions.
internal sealed class Character
{
private readonly string name;
internal Character(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.name = name;
}
internal string Name { get { return name; } }
}
You haven't put a class in another class at all! You've just put 2 classes in the same file, which is really a personal preference. (I have some files with 5-6 interelated classes edit: omg Jon Skeet disagrees with me oh noez! :) ).
So in your example, you have 2 classes.
Do you mean the two classes are in one file?
One class per file is generally accepted as the way to do it, and in some languages is necessary.

Can you create private classes in C#?

This is a question for the .NET philosophers:
It is my understanding that Microsoft consciously denied use of private classes in C#. Why did they do this and what are their arguments for doing so?
I, for example, am building a large application that includes a reporting tool. This tool uses a lot of business objects that are used only within the reporting tool and not in other parts of the project. I want to encapsulate them for use only within the reporting tool itself.
Great decision is creating separate project in VS for this tool, and I'll do like that, but I'm interesting, what if I can't do this - for exmple our architecture wasn`t good enough, and we have big single project.
Behind "private class" I mean a class that can't be used in any other namespace, except its own.
My question was not - how can I simulate this, or do in another way. I'm just wondering, why not use private keyword with class keyword without any parent classes. I`m thinking there should be some reason, and I want to know it
Allowing classes to be private to a namespace would achieve no meaningful level of protection.
Any assembly in the world could simply reference your dll, and start writing code in your namespace which accesses your supposedly private classes.
I think that's possibly the answer you'd get from Microsoft.
There's a workaround for this, but you might not like it.
Instead of using a namespace to scope your classes, use a public static partial class:
Before:
namespace MyCompany.Foo {
class Bar { }
public class Baz { }
}
After:
namespace MyCompany {
public static partial class Foo {
private class Bar { }
public class Baz { }
}
}
This construct, like a namespace, can span multiple files in the same project. But unlike a namespace, it cannot "escape" from your project (other projects cannot define other members inside Foo).
There's an added advantage that you can have utility methods that seem to have no class for code inside Foo.
The disadvantage is that, to use your non-private classes outside of your fake namespace, you have to reference them inside Foo:
using MyCompany;
// ...
var baz = new Foo.Baz();
This can be mitigated by using an alias for the class:
using Baz = MyCompany.Foo.Baz;
// ...
var baz = new Baz();
But you'd have to do it for each non-private class that you want to use.
UPDATE
It's interesting to note that C# 6 will have static using statements, which could effectively improve this proposal to use a public static partial class as a "module". You would just "use" the "module" to access its types directly.
Hopefully, it will work like this:
using MyCompany.Foo;
// ...
var baz = new Baz();
Just as if Foo was a namespace.
You can create a private class, as a member of another type:
public class Outer {
// ...
private class Inner {
// ...
}
}
and Inner is only visible to members of Outer.
At the outermost level (i.e. in a namespace) private as per its definition would not make sense (since there is nothing to be private in). Instead use internal (visible to the containing assembly's members only).
You can define a private class, but it can only be used by its containing class.
If you want a class that is only visible within a particular assembly (DLL/EXE/etc.), then you should declare it as internal (Friend in VB)
True but you can get a pretty close simulation of this with internal classes and the internalsvisibletoAttribute if the namespace is split across multiple assemblies.
Also remember that a class within another can be private to the outer class. The outer class can be considered a namespace for this purpose.
So I guess you want to do this
namespace Baz
{
private class foo
{
private int _bar;
}
}
If yes. Then what is the purpose foo will server. At namespace can you be more restrictive than internal , and make any use of the class.If I could do this where will I use this .
That is why you have this compile time validation.
Now Inside a Public Class it makes sense to have a private class. I cannot explain it better this Private inner classes in C# - why aren't they used more often?.

C# Beginner, writing/calling a Method

When we write a method, say an easy one like
void myMethod()
{
// code here
//
}
and we call it from within Main(), it's done essentially this way:
Program myProgram = new Program ();
myProgram.myMethod();
Obviously, myProgram is entirely arbitrary (taking into consideration, of course, coding conventions) but what's up with the reference to Program?
You are declaring your method myMethod inside a class called Program. Since your method is not a static method (i.e. it is not static void myMethod()) it requires an instance of Program in order to work. Therefore you need to create a new instance of Program in order to invoke myProgram.myMethod() on it. If myMethod were static, you could have called it simply by Program.myMethod() or, since you're already inside that class to begin with, myMethod() (since the current class name is implied for static methods).
Program is a class, which contains methods. By default the only method it contains is static void Main(...).
If you add your non-static method myMethod it doesn't belong to the class Program, but rather to instances of Program (called objects).
Static methods (like Main) can be called directly from the class:
Program.Main(...);
Non-static methods must be called from objects of the class:
Program program = new Program();
program.myMethod();
Classes are designed to group together like functionality. Program isn't a good place to put these. You should create other classes, and use them throughout your code.
By using classes you keep like code together, and provide a mechanism to reuse the same code over again from different places. You can create as many different instances of 'Program' as you like, from many different classes, and invoke the 'myMethod' method on each of them.
For instance you might have a ClassRoster and a Student class, which can be used like this in the ClassScheduler class:
ClassRoster roster = new ClassRoster();
Student studentOne = new Student();
studentOne.StudentId = "123456";
roster.EnrollStudent(studentOne);
Program is the type, that defines myMethod in your question. In C# methods are defined by types.
You can either call methods via an instance of the defining type or via the type itself (if the method is static). Since myMethod isn't static, you need an instance of the type Program to call it.
use this:
public void myMethod()
{
// code here
}
in main method:
Program myProgram = new Program();
myProgram.myMethod();
Thanks everyone.
I went back to my code; I added static in front of myMethod, and in doing so the Program myMethod = new Program() became unnecessary (uncompilable? illegal?), and it can be called simply by writing myMethod() Obviously I need to study up on what static does and how it affects methods/classes!
I'm actually only in week #3 of my .NET class... our instructor, while very smart, leaves something to be desired in the teacher category. The assigned text for the class is only so-so in my opinion, at least for me and how I learn (Programming C#, O'Reilly) This is a very good community, thanks!

Categories