What can I do with a protected/private static variable? - c#

I see I can write :
protected static
in my C# class (in my case, an aspx.cs). As well as :
private static
What does it means? Static is accessible everywhere. Why protected/private?

The definition of static isn't "available everywhere". It is a variable shared across the type it is declared within in the scope of an AppDomain.
Access Modifiers do not alter this definition, but obviously affect the scope of access.
You are confusing the static modifier with access modifiers. A static variable still needs accessibility defined. In your example, private static variables are only accessible within the type it is defined in, protected would be accessible within the type and any derived types.
Just a note, be aware that IIS (hosting ASP.NET applications) recycles worker processes, which will flush any static variable values that are alive at the time.

If you declare a variable as a Private then you are not able to access it outside the current class and if declare as a Protected then only the derived class is able to access that variable..In your example the basic meaning of private and Protected is not changing so it does not matter how you declare it Static or simple one...
class Test
{
protected static int var1;
private static int var2;
}
class MainProgram : Test
{
private static int test;
static void Main(string[] args)
{
Test.var1 = 2;
Test.var2 = 5; //ERROR :: We are not able to access var2 because it is private
}
}
In above code you can see if we want the static variable is accessible only in the current class then you need to make it as a Private.

private
The type or member can only be accessed by code in the same class or struct.
protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.
Static Modifier
Static methods are called without an instance reference.

static does not mean it is accessible everywhere. You still need protected/private to define visibility.

Use protected if you only want the variable to be accessible through certain classes, for instance when using polymorphism and inheritance. Public makes it always visible within the scope and private is pretty obvious.

One use is that you can create private static fields, and expose using public static methods/properties (to apply some custom business logic like singleton, etc)

Static is a modifier.. And protected and private are access modifier.
Access modifier specify the scope of the variable.
Static modifier is used when we want field or method to be singleton thus we don't have to access them by creating the object , rather they can be called through class name directly

Related

Default Constructor with Private accessibility

According To Microsoft Class always contain Default Constructor which is private then how is possible to initiate the Object in another Class.
You are simply misreading that page. For a class without a defined constructor:
class C {}
There exists a default, public constructor, C().
If you explicitly declare a constructor, then that default constructor won't exist. If you declare your constructor like:
class C
{
C()
}
then it will be private, as all class members are private unless an explicit public, internal or protected access modifier is used.
You've missed the most important part of the article:
A private constructor is a special instance constructor. It is
generally used in classes that contain static members only. If a class
has one or more private constructors and no public constructors, other
classes (except nested classes) cannot create instances of this class
The common use case they show in the article talks about using static members only via the said class, like this:
class NLog
{
// Private Constructor:
private NLog() { }
public static double Foo = 3.284;
}
Classes do not have default private constructor, they have a public one (except for abstract classes):
If the class is abstract then the declared accessibility for the
default constructor is protected. Otherwise, the declared
accessibility for the default constructor is public. Thus, the default
constructor is always of the form
"The declaration of the empty constructor prevents the automatic generation of a default constructor" (https://msdn.microsoft.com/en-us/library/kcfb85a6.aspx)
If you declare an empty constructor (whether it is private or not, it doesn't matter), you prevent the generation of the default one (which is always public).

Static global Variable in C# has file scope?

in C++ you can define the scope of a global variable with the static keyword to be at "file scope" Is it the same in C#?
thanks!
C# does not have a concept of file scope. Something similar can be achieved by internal that allows you to restrict the visibility to the declaring assembly.
The static keyword: In C++, static can be used both to declare class-level entities and to declare types that are specific to a module. In C#, static is only used to declare class-level entities.
Useful link for you,
C# for C++ Developers
I don't know what is the file scope but you can define your variable in the class level and you can access it inside of your class whenever you want.
public class MyClass
{
public static object SomeVariable;
...
}
That is the largest scope for a variable in C#.
if you mean to make a class called Varriables and then call it each time like: Varriables.myNewVarriable then all you need to do is make a class called Varriables and then use: public static
public class Varriables
{
public static int myNewVarriable = 14;
}
then just call it from another class:
if (Varriables.myNewVarriable == 14)
{
Console.Write("True");
}
>>>True
Static member fields can be only public, internal (visible only in current assembly and declared friend assemblies) or private.
Additionnaly you can considere nested classes (even a public static field of a private nested class isn't accessible outside the outer class).
Another way to protect "Hot" shared members (not directly static, but that can be a member of a static instance) is to define an interface (that may be internal) giving access to this member. Then to implement the interface explicitly (specifying the interface name as dotted prefix of the member name) in the class of your static instance. To access this member the authorized code have to first cast the static instance to the interface.
Generally you have to considere using only internal access. Assuming that code in your current assembly will behave well concerning internal access members or types.
Maybe you can be more explicit on your needs and we can find an optimal solution.

Does Static class create an instance? msdn says i doesn't, but why constructor then?

I came across trying to understand the difference between singleton object and static class
and the simplest information I see everywhere is that static class DOES NOT create an instance while singleton requires to
But why the hell can I have the static constructor from static class? what does that mean? doesn't it create an instance?
if you run simple code with breakpoint on static class constructor you will see it reaches it
I'm confused, anybody?
But why that hell can I have the static constructor from static class? what does that mean? doesn't it create an instance?
No. The static constructor allows you to initialize static members of the class (basically, the static state for that class).
With the singleton pattern, the static constructor (or a static inline initializer) often creates an instance, but that instance is still created via the normal, non-static constructor. It's then stored within a static variable (the single "instance" variable).
Lazy-initialized singletons will avoid that, and initialize the static variable on demand.
A static class is a different thing - a static class will never work as a singleton, since you can't create an instance of a static class. Static classes are specifically intended to be used when you will never create an instance.
A singleton will (typically) be created by having a non-static class, but using a private constructor (so the instance can only be created within that class). There will be a static property used to retrieve a single instance of that class. The class instance will either be created on demand or within the static constructor.
The static constructor is just a place where you can initialise your static member variables. You don't need a static constructor - you can initialise the static member variables inline instead, but I think it's tidier to put them in the static constructor.
Remember that even though you don't instantiate the static class, you do instantiate its static members, and it's nice to have a place to do it. This is an improvement on the way you have to do it in C++.
Note that your class doesn't need to be static in order to have a static constructor. You can have a non-static class that provides both an ordinary constructor and a static constructor. Same rule applies.

instance of a class and derived classes can change a static member of the class indirectly through a non-static method in c#

public class Class1
{
public static string Name="foo";
public void ChangeName(string _name)
{
Name=_name;
}
}
in some other class..
Class1 _c=new Class1();
_c.ChangeName("bar");
and the Name gets changed.. an instance changing a static member!
I thought a static member is available only for a Class. If a Class wants it can change its static members.
But here an instance is able to change it indirectly.Shouldn't an instance not be able to change it? When we create an instance it occupies its own space in the heap without having access to the static members of the Class. So what is really happening here?
The important part is
public static string Name="foo";
which creates a changeable static property. This allows for
Class1.Name="bar"
from outside the class as well as from inside the class - inside the class you can shorten this to
Name="bar"
which is exactly what is called via ChangeName("bar")
You might want to consider
public static readonly string Name="foo";
EDIT
If you want to be able to change the value only from within static methods, consider using a setter/getter construct with appropriate setter logic.
No, an instance is not kept from accessing static members. Instances are separate from each other, but static members are available both to static methods and instance methods.
As you have made it public, it's not even only methods in the class itself that can access it. You can change it from anywhere:
in some other class...
Class1.Name = "Albert";
MSDN clearly states :
"While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field."

Why have all static methods/variables in a non-static class?

I have come across a class which is non-static, but all the methods and variables are static. Eg:
public class Class1 {
private static string String1 = "one";
private static string String2 = "two";
public static void PrintStrings(string str1, string str2)
{
...
All the variables are static across all instances, so there is no point having separate instances of the class.
Is there any reason to create a class such as this?
Was the class written back in the .NET 1.x days? Static classes didn't appear until C# 2.0.
No. Make it a static class.
No. Some people dont realise that classes themselves can be static, and so don't include in the class definition. This is useful because it provides better intellisense options and ensures that future methods are added statically.
This also implicitly seals the class.
Static class provide :
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor.
No, if there are no instance members in the class then it should be static.

Categories