Static global Variable in C# has file scope? - c#

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.

Related

Do C# classes default to instance or static classes if not specified?

When declaring a class in C# without specifying if the class is a static or non-static class which will it default to?
EDIT: Here's an article I wrote based on this discussion.
https://hackernoon.com/c-static-vs-instance-classes-and-methods-50fe8987b231
If you don't declare the class as static then its members can be either static or non-static.
A static class can only have static members.
You can invoke non-static members only on instances of the class.
You can invoke static members only on the class itself.
Also, in your class declaration, there are no parentheses.
If the "static" is not specified, it will require an instance of the class to be used (Unless the member itself is specified as static).
If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable.
From: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes
A class is always an instance class unless you specify otherwise

If I declare an internal class, what the default access level of internal members be?

I'm building a DLL with some basic functions. Long story short, I'm making a few static classes for the use by devs. These classes use some other classes that do the dirty work, which I marked as internal because I don't want people to access them.
The question is: If I declare a class as internal, what the access level of his members will be?
I'll have to mark as internal all of its members or they are automatically labeled as internal too?
It's a good 2 hours I'm googling and searching in stackoverflow and I'm struggling to find a clear and straight answer which doesn't include 1000 speculations, technical not-so-probable hypotesis and useless decorations...
MSDN is confusing as usual (never found a clear answer on msdn).
From what I can read here http://msdn.microsoft.com/en-us/library/ms173121.aspx I guess that no matter how you set a class access level, all his members will be private (methods, variables and so on).
Help, I don't know
The question is: If I declare a class as internal, what the access
level of his members will be?
The default will be private. If anything else, then it depends. If they are anything other than public, then the access modifier applies as described on MSDN (e.g. not visible outside of the assembly).
However, in the link you posted, there is one gotcha which applies to non-static classes:
Normally, the accessibility of a member is not greater than the
accessibility of the type that contains it. However, a public member
of an internal class might be accessible from outside the assembly if
the member implements interface methods or overrides virtual methods
that are defined in a public base class.
In relation to the last paragraph, since static classes cannot implement interfaces or inherit other classes then you can rest assured. As long you declare your static class internal, the members will not be available in other assemblies (unless your devs use reflection).
To exemplify how it does work for non-static classes:
Assembly 1
public interface ISomePublicInterface
{
int GetValue();
}
internal class InternalClass : ISomePublicInterface
{
public int GetValue()
{
return 100;
}
}
public static class SomeFactory
{
public static ISomePublicInterface GetInternalInstanceAsInterface()
{
return new InternalClass();
}
}
Assembly 2
ISomePublicInterface val = SomeFactory.GetInternalInstanceAsInterface();
Console.WriteLine(val.GetValue()); //-->> Calls public method in internal class
Console.WriteLine(val.GetType());
Guess what the output is?
Assembly1.InternalClass
So, now you have access to the type outside of the assembly and via reflection someone could call other internal methods (it's not the only way to get it).
From MSDN only
The access level for class members and struct members, including
nested classes and structs, is private by default.
interfaces default to internal access.
Hope this table helps:
Members of Default member accessibility
---------- ----------------------------
enum public
class private
interface public
struct private
Also check this MSDN
Private unless otherwise stated. However, public will have same result as internal.
If you later promote a class from internal to public, then creating public class objects will become visible, whilst internally scoped methods will stay internal.
You might want to consider behaviour in case your class scope gets updated.
Another stack overflow question.
If u Declare any class as "internal" then its means you can access this class in same assembly. But what kind of access specifier you use for class member is decide they are accessible are not in different class in same assembly.
All the members of internal class would be internal and will be accessible with in the same assembly and will not be outside neither class nor members.
If you want to access class in other assemblies, make the class public and member you don't want to be accessed outside assembly make them internal.

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

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

My C# Private Class is accessible anywhere inside the DLL, then whats the use of internal?

I have ClassLibrary project in C# and all my 'private classes' (under different namespace) are accessible to each other inside the same assembly (project).
Class1.cs
----------------------------
namespace MyClass1App
{
private class Class1{}
}
Class2.cs
----------------------------
namespace MyClass2App
{
private class Class2{}
}
Now Class1() can access and create instance of Class2() class [like... new MyClass2App.Class2() ]. and yes, these classes (Class1() and Class2()) are not accessible outside the assembly. Its the same behavior when these classes are made as 'Internal'. Can someone help me understanding whats the actual use/difference of 'private' and 'internal' access specifiers when applied on class level?
Thanks!
For normal classes you can only apply public and internal other access modifiers don't make sense.
Nested classes can have all access modifiers types.
You should not be able to declare a class as private at the namespace level. You can only have a private class if it is embedded within another class.
I get an error if I try to do this:
namespace MyApp
{
private class Class1
{
}
}
This is the error message:
Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal
Access Modifiers (C# Programming Guide)
Class or struct members can be
declared with one of five types of
access. They can be public or
internal, like the classes and structs
themselves. A class member can be
declared as protected using the
protected keyword, meaning that only
derived types using the class as a
base can access the member. By
combining the protected and internal
keywords, a class member can be marked
protected internal — only derived
types or types within the same
assembly can access that member.
Finally, a class or struct member can
be declared as private with the
private keyword, indicating that only
the class or struct declaring the
member is allowed access to that
member.
Duplicate Question:
Internal vs. Private Access Modifiers

C# inheritence and static classes

Why can't a static class be inherited into a normal class?
If B inherits from (is a subclass of) A, that means an instance of B can be stored in a variable of type A, and its virtual methods will call those of class B.
For static classes, you don't have the concept of an instance of the class, so there's no way to inherit. You might have better luck with a static (singleton) reference to a regular class.
From Static Classes and Static Class Members (C# Programming Guide)
Creating a static class is therefore
basically the same as creating a class
that contains only static members and
a private constructor. A private
constructor prevents the class from
being instantiated. The advantage of
using a static class is that the
compiler can check to make sure that
no instance members are accidentally
added. The compiler will guarantee
that instances of this class cannot be
created.
Static classes are sealed and
therefore cannot be inherited. They
cannot inherit from any class except
Object. Static classes cannot contain
an instance constructor; however, they
can contain a static constructor.
As an alternative to inheriting from a static class, you can assign extension methods to interfaces.
You can not inherit a static class - The reason is simple. Static classes are marked as abstract and sealed in compiled IL which can be neither instantiated nor inherited.
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Source:
Why can't I inherit static classes?

Categories