C# Beginner, writing/calling a Method - c#

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!

Related

Confusion with System.ApplicationId;

Reading and messing around to understand static classes and static methods and their differences with non static methods and their usage which i still don't get except maybe for the Main method which must not be made an instance(object) of a class.
Why if i try to use:
using static System.ApplicationId;
public class Program
{
static void Main()
{
Copy(SOMETHING)// Copy method doesn't exist
}
}
Then try to use a method from ApplicationId like Copy();
The IDE? can't find the method?
Doing the same with:
using static System.Console;
public class Program
{
static void Main()
{
Writeline("Hello"); // OK
}
}
Then try to find a method from Console like WriteLine();
It can find it and i can use it.
Why does that happen?
My understanding is That those are both static members? Isn't that the reason why i cant make instances of those 2 classes? Yet i can use the methods in the second example but not in the first one since it seems that it doesn't let me (error: copy() doesn't exist in the current context...).
The short answer is that you wouldn't use the static keyword in a using statement for non-static namespaces like System.ApplicationId
To use methods on a non-static (instance) class, you have to first make an instance of it using new. The tl;dr part followsTo avoid having to write out the namespace prefix System. every time you want to refer to ApplicationId, you can add
using System;
and then in the class, you can get to the someMethod() method with:
new ApplicationId().someMethod();
Now let's talk about static:
Before C# version 6, you just couldn't use a using statement on a static class, so to get access to a static method like
System.Console.WriteLine()
you'd first add the non-static parent (System) with
using System
and then refer to the static method using the namespace
Console.WriteLine
With the using static syntax, you add the 'Console.' part of the namespace once per class on the using statement like so:
`using static System.Console;`
and then you can use WriteLine() instead of Console.WriteLine. I have to guess that the WriteLine() method has got to be the most common use case for this functionality.
If you check out https://msdn.microsoft.com/en-us/library/system.console%28v=vs.110%29.aspx it shows that System.Console is a static class, so using static is appropriate there.
However, System.ApplicationId is non-static (see https://msdn.microsoft.com/en-us/library/system.applicationid%28v=vs.110%29.aspx) so you can't use using static.
The answer is simple, the methods in ApplicationId are not marked as static.
Let's see the difference between static and instance methods:
Static method:
Console.WriteLine();
******* *********
^ ^
class method
name name
Instance methods:
Random aRandomObject = new Random();
aRandomObject.Next();
************* ****
^ ^
name of an method
instance of name
Random
As you can see here, you need an instance of that class in order to use non-static methods. But for static methods, you don't need an instance.
The using static directive allows you to omit the class name when you call a static method.
"But why doesn't it allow us to call instance methods like this?" you asked. As I have said above, you need an instance to call instance methods. If you only write the method name to call the method, how can the compiler know what instance do you want to call it on?
ApplocationId is not a static class, so you need to create an instance of it.

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].

Are System, console, Namespace classes or already instances?

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.

Is there any reason to not use the static modifier in C#?

I am pretty new to C# programming, and I am still learning. I was wondering if there is any particular reason to not use the static modifier when creating a method, for me it just seem much simpler. I tried looking at MSDN but that isn't much help if I don't know what half the words mean.
For example this:
using System;
namespace StaticModifier
{
class Program
{
static void Main(string[] args)
{
SayHi();
}
static void SayHi()
{
Console.WriteLine("Hi");
}
}
}
Seems much simpler than this:
using System;
namespace StaticModifier
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.SayHi();
}
void SayHi()
{
Console.WriteLine("Hi");
}
}
}
So would anyone be willing to explain? Keep in mind that I am pretty new so please keep it simple :)
A non-static method of the class Program provides the current instance of the class Program..
Since Program doesn't contain any variables or properties that are used, you don't need to molest your CPU with unnecessary objects.
And Program p = new Program(); is not the way you would instantiate your "Program". The Main() method is static and is usually contained within a static class with static methods. You can't call dynamic methods from a static method, since there is no instance of the object.
TL;DR
If you want to pass this (the current object) to the method and your method utilizes its properties, then don't use static. Otherwise there is absolutely no reason not to use static!
You wouldn't use the static modifier if you had a class that would require more than 1 instance of itself. For example if you have a class named car that included the static keyword you would only ever be access the members of that class via the static reference of that class. So you could never have 2 instances of a car object.
Which depending on what your program is trying to do maybe appropriate. However you may look to use the static keyword if you had a class names player score. As this would only ever exist once, and unless you have more that one player you would want 1 instance of the player score. Which means you could either consider a singleton instance or just have a static class.
There are many many reasons why you either would or wouldn't make use of the static modifier. However to some up when you should use it is impossible and depends on the specific scenario of the application you are creating.

What does a static modifier on a constructor means?

I saw this kind of code at work:
class FooPlugin : IPlugin // IPlugin is a Microsoft CRM component, it has something special about it's execution
{
static FooPlugin()
{
SomeObject.StaticFunction(); // The guy who wrote it said it's meaningful to this question but he can't remember why.
}
}
Any idea what does a static modifier on a constructor mean and why in this case it is required?
This is the static initialization of the class.
It would be called when you use a method, a field, a property or anything else of the class. In other word, it would be called the first time you use the class.
See static constructors on MSDN
You can also initialize static stuff here.
In your example it seems that whoever wrote that wanted to call SomeObject.StaticFunction() once before people will use FooPlugin, probably so it will be initialized before using FooPlugin.
Note that there is some performance hit when you use it and visual studio (using code analysis) can let you know that you better off initialize the static fields inline.
See CA1810: Initialize reference type static fields inline on MSDN
It defines the static constructor for the object.
A static constructor is used to
initialize any static data, or to
perform a particular action that needs
performed once only. It is called
automatically before the first
instance is created or any static
members are referenced.
Read more at MSDN - Static Constructors (C#)
I can't say why it's required in your particular case, but the motivation for a static constructor is usually one of these:
All instances of the class need
access to the same instance of an object, or
Initialization of some external object
is a prerequisite for all instances
of the class (seems like the case in your example) or
Initialization of some data structure or service takes takes too much time to do repeatedly (a variation of the first case).
Here's a simpler example of when a static constructor is useful. The following class has some static fields. The first can be initialized inline with its declaration, but the second one can't. Static constructor to the rescue. The key guarantee it provides is that no part of the class can be accessed before the initialization code runs.
class NeedsStaticConstructor
{
private static Size s_size = new Size(100, 100); // can be done inline
private static StringFormat s_format; // more complex initialization needs code
static NeedsStaticConstructor()
{
s_stateTextFormat = new StringFormat(StringFormatFlags.NoWrap);
s_stateTextFormat.Alignment = StringAlignment.Near;
s_stateTextFormat.LineAlignment = StringAlignment.Far;
}
}
A static constructor is used to initialize class-wide (i.e. static) members, as opposed to instance members.
Just to add to the above answers, static constructor (or static blocks as in the case of Java) get executed only once when the class is first loaded in to memory. The objective is to initialize static fields, which otherwise would assume the respective default value of the data type. Sometimes I use static constructors to build an object model that I want to use throughout the life time of the application.

Categories