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.
Related
It's extremely lazy, but I'm wondering if it's possible to have two names point to the same static class in essence.
I have a long and descriptive static class name BusinessLogicServiceUtility (as example) and it's looking rather long-winded in code.
I'd love to use BLSU as an alternative, so I tried extending the long class with my short class name:
public static class BLSU : BusinessLogicServiceUtility
{
}
Which probably looks noob but as it turns out, it doesn't work.
It looks as though I could wrap each method in the long class with a method inside the short class, but there's a lot of methods, which makes maintaining it a pain and circumvents the whole laziness goal.
Is there a way of assigning two names to one static class, or some other method simply "extending" a static class?
You can create an alias for a type:
using BLSU = Your.Namespace.BusinessLogicServiceUtility;
Accessing members of type:
BLSU.SomeStaticMethod();
With C# 6 you can even go further - access static members of a type without having to qualify type name at all:
using static Your.Namespace.BusinessLogicServiceUtility;
Accessing members of type:
SomeStaticMethod();
Further reading: using Directive (C# Reference)
In addition, you can use using static that will allow you to use the methods without prefixing them with the class at all:
at the top of the file :
using static BusinessLogicServiceUtility;
and say you have a method public static DoLogicThings() in your static class, you can access it directly now:
public void SomeMethod()
{
DoLogicThings();
}
this was added in C#6.
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.
Lets assume i got this class:
public class Utlities
{
int Age;
public static void DoSomething()
{
Age ++;
}
}
My questions to this:
Does anyone from outside - can access DoSomething() in same time? - assuming YES
If answer on 1. is YES then if couple classes executing this method the value will be changing without any problems?
Class is non static but method is static so is the method only accessible one time in specific time?
What in case i have couple instance of that class if other classes will access specific instance of class Utilities true is that DoSomething method will be shared/the same across all instances of class Utilites or for each instance of Utilities class other outside classes will be accessing different DoSomethingmethods?
Lets take another example:
public class Utlities
{
static int Age; // <------------------------------------
public static void DoSomething()
{
Age ++;
}
}
How it will be in this case?
And last:
public static class Utlities //<-------------static now
{
static static int Age;
public static void DoSomething()
{
Age ++;
}
}
As class is static now all inside have to be static - does it mean that only one outside class can access it in same time?
Last questions as i want to create some help class which inside i would have common methods that could be useful in my program should i use static class with static methods or non static class with static methods - please of explanation here as well.
Declaring a variable/class/method as static wont change the accessability.
As an example, a static method belongs to the class itself, meanwhile a nonstatic method belongs to each object of that class.
If you have a static variable
static int ageCounter;
all objects of the class, holding this variable, will see the same ageCounter
In addition to that, your question was about multiple calls of that static method by different classes. If this happens in a single thread you wont have problems at all. Trouble starts if different threads try to work on the same data.
Apart from the fact that your first example will not compile (can't access instance field from a static method), static doesn't restrict use of that method. It is entirely possible that multiple thread access that method at the same time.
Instead static means that you can access that method (or field) without an instance of that Utlities class.
You can just use
Utlities.DoSomething();
instead of (which doesn't even compile)
var myutls = new Utlities();
myutls.DoSomething(); // <-- compile error: cannot be accessed with an instance reference
In the static class example, you can't even do a new Utlities(). The compiler will not accept it (Cannot create an instance of the static class).
Be careful with a static value like that static int Age: this means that your application can store just one Age value (which isn't always what you want)
(Presuming that your Age field was meant to be static, too.)
Declaring a variable/class/method as static wont change the accessability.
As an example, a static method belongs to the class itself, meanwhile a nonstatic method belongs to each object of that class.
In addition to that, your question was about multiple calls of that static method by different classes. If this happens in a single thread you wont have problems at all. Trouble starts if different threads try to work on the same data.
Last, you mentioned the missing static modifier on the class. That modifier is only there to prevent a class from being instantiated and can be used if (and only if) all members of the class are static, too.
I have created folders in my project named Classes, Forms, and Models.
Let's say my project is named ABC, so the folder hierarchy is:
ABC
Classes
Forms
Models
In \Models\, I have a class named ApplicationModel.cs, which contains a public method named GetApplications().
However, when I call that method from elsewhere in the same ABC project, I get, "The name 'GetApplications' does not exist in the current context"
I've added:
using ABC.Models;
to the calling class, but it makes no difference. I right-clicked GetApplications() to hopefully see "Resolve" there, but no go.
What must I do to access my own public method?
It would be helpful to see the definition of GetApplications() and the code that's attempting to call it, but I assume it's either a static or an instance method of the ApplicationModel class. In either case, you may have made your code aware of the namespace of the ApplicationModel class with the using statement, but the method must either be called on the class or an instance of the class, like so:
If GetApplications is a static method,
var applications = ApplicationModel.GetApplications();
If it's an instance method:
var appModel = new ApplicationModel(); // or, retrieve the instance from elsewhere...
var applications = appModel.GetApplications();
One way or another, you must refer to the class containing GetApplications in order to call it. If this doesn't help you solve the problem, please edit your question to contain the definition of the method, and the calling code.
Sounds like you're using a static function. Did you forget the static keyword?
A static function "runs" from a class, not an object:
public static string[] GetApplications()
It is hard to give definitive advice without some code on how you are trying to call that method. I can think of two possible ways:
either you are trying to call the method via the ApplicationModel class(ApplicationModel.GetApplications()), in which case you need to declare the method static
or you need to call the method on an object, but you are using the type -- in this case declare/create an object of type ApplicationModel and call the method on that object; (e.g. ApplicationModel model = new ApplicationModel(); model.GetApplications();)
Looks like the class is not marked as public.
You class should be
namespace ABC
{
namespace Models
{
public class ApplicationModel //class needs to be public is accessed outside the namespace
{
}
}
}
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!