I have seen it in many projects. Why do developers use internal classes to store the constant variables in C#?
For instance:
internal static class Constants
{
public const double Pi = 3.14159;
public const int SpeedOfLight = 300000; // km per sec.
}
Simply, the designer decided that this class need to be used within the same assembly. And it is not to be exposed to or accessed from any project referencing the assembly.
When you download a Nuget package, you can't access classes that are internal. The developers decided that you don't need to access these. So these values are "private" for this package.
More on access modifiers:
public :Access is not restricted.
protected :Access is limited to the containing class or types derived from the containing class.
internal: Access is limited to the current assembly.
protected internal : Access is limited to the current assembly or types derived from the containing class.
private : Access is limited to the containing type.
Because when constants are publicly exposed (instead of internal), the danger exists that when an outside assembly references them, it may become "out of date" when the assembly that declares them is updated with new constant values, but the referencing assembly is not re-compiled.
Say, for example, the referenced assembly containing the "updated" constant values forms part of a "plugin" architecture, where a new version of the plugin could simply be "dropped" into the referencing application's folder without recompiling and redeploying the application. Even if the application that referenced a constant from the "plugin" assembly that originally declared it, the application will not use the new updated values, and will continue using the old ones instead.
This happens because when the compiler sees a constant, it "inlines" its value into the expressions or statements that contain ("reference") it, wherever that may be.
To solve this problem, and you really want to expose a "constant" to the outside world, rather declare the symbol as public static readonly. That way, if the value is ever updated, any outside assemblies that reference it will automatically use the update value(s), even without needing a recompile.
But if you really want to use const instead, make sure it is really a constant that will never change, i.e. laws of nature, physical constants, like Pi.
While most answers describe the meaning of internal they are missing a part of the question I think: Why put constants in a inner class?
This is mostly because it can they desire to identify constants through something feeling like a namespace:
double myValue = Constants.Pi * 10;
Or
double myValue = OtherClass.Constants.Pi * 10;
Without the inner class they would look more like members/properties. At least when they do not use UPPER_CASING for the naming.
To make the answer complete: The internal is used to protect the constant against using them outside of the assembly.
Related
In C# we can define any member as Internal, which makes it only visible inside the current assembly:
internal int Age;
I was wondering if its possible to reverse this effect, marking it private/protected to this assembly, but public to a specified other assembly.
This sounds completely insane, but we have a valid reason to do this. We're using the Unity3D game engine, where all of our game-logic is in the 'runtime' assembly. We can also define custom editors for these classes, which allow us to create custom UI controls in the IDE. Those editors live in a special 'editor' assembly.
This editor assembly frequently needs more information about a specific type in the runtime assembly then we'd like to expose to our own assembly. Our current solution is to get the specific private/protected member via Reflection, but i'd like to know if there is a better solution.
You can't change the visibility of these members.
One option is to create an interface that exposes the desired members, and then explicitly implement it:
class MyClass : IEditable
{
internal int Age { get; private set; }
int IEditable.Age { get; set; }
}
You'd have to cast MyClass to IEditable to access the properties in this case. It would also help identify when changing the runtime assembly would break the editor.
It does sound like a design issue. The data that must be known to both assemblies should be isolated to its own assembly and referenced by each of them. Failing that, you could look at creating a wrapper/adapter that publicly exposes the hidden data in the core assembly, in a read-only way that is available to your other assemblies.
In C++ I'd often create a code file containing constants, enums, #define-s, macros etc.
What's the best practice for that in C#? Do I create a static class and fill it with that data? or is there some other way ?
You don't need a static class for enums - they can be top-level (meaning: namespace level). Yes, you need a class for constants (and a static class would suffice), but I would tend to have multiple classes - one per intent. There is no need to cram them all together.
In C#, any #define only apply to that file, so there is not much point having a class for them (put them in the project / build-script instead). And macros don't exist.
If you have some items you want to define Globally, like a set of strings, I would use a static class with Static properties. I would do that if you are going to use it in more than 1 place.
If you are going to use a defined string for example in just once place, then I would put it in the class that is referencing it.
It is very important to use properties and not expose members. I have found with C++ developers I have worked with when they move to C# they expose members because they have no need for "the special logic of a property". While that may be true when you initially are writing the code. If you expose it as a member and need to do special logic then you have to refactor in a major way. While if you begin as a property then you can add the logic with no refactoring.
For Enums I tpyically define an Enum.cs file inside the folder that represents the namespace. Rather than define them inside a static class.
Macros:
Macros don't exist in C#.
#Defines:
defines are very restricted and only really used for conditional compilation. You should define them by using the project properties (or in your msbuild script) instead.
Enums:
Enums should each go in their own separate file. They don't need to be within a class, they just go directly in the name space.
Constants:
Personally I try to keep constants to a minimum, and private within a class where possible.
If you do have to make them public and globally available, use a static class (or a normal class if they relate directly to one nicely). Try to group them into classes by their use.
If you are talking about string constants, you could consider using a resource file instead if they are localizable strings.
Usually there is a class or struct for which your enum etc. particular applies. I put it in that file, under the class. It's easy to get to the definition from anywhere it's used in code. When possible, I try to put all similar entities for a namespace (or other logical grouping) in the same place.
I'd already object to that practice in C++.
Define that stuff where you need it and not in a single "dump" file. This kind of file tends to accumulate huge amounts of unused stuff over time. And it's hard to clean up because who knows, which parts of your code is using it...
I want some variables to be global across the project and accessible in every form. How can I do this?
yes you can by using static class.
like this:
static class Global
{
private static string _globalVar = "";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
}
and for using any where you can write:
GlobalClass.GlobalVar = "any string value"
The consensus here is to put the global variables in a static class as static members. When you create a new Windows Forms application, it usually comes with a Program class (Program.cs), which is a static class and serves as the main entry point of the application. It lives for the the whole lifetime of the app, so I think it is best to put the global variables there instead of creating a new one.
static class Program
{
public static string globalString = "This is a global string.";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
And use it as such:
public partial class Form1 : Form
{
public Form1()
{
Program.globalString = "Accessible in Form1.";
InitializeComponent();
}
}
Or you could put your globals in the app.config
You can use static class or Singleton pattern.
One way,
Solution Explorer > Your Project > Properties > Settings.Settings. Click on this file and add define your settings from the IDE.
Access them by
Properties.Settings.Default.MySetting = "hello world";
public static class MyGlobals
{
public static string Global1 = "Hello";
public static string Global2 = "World";
}
public class Foo
{
private void Method1()
{
string example = MyGlobals.Global1;
//etc
}
}
If you're using Visual C#, all you need to do is add a class in Program.cs inheriting Form and change all the inherited class from Form to your class in every Form*.cs.
//Program.cs
public class Forms : Form
{
//Declare your global valuables here.
}
//Form1.cs
public partial class Form1 : Forms //Change from Form to Forms
{
//...
}
Of course, there might be a way to extending the class Form without modifying it. If that's the case, all you need to do is extending it! Since all the forms are inheriting it by default, so all the valuables declared in it will become global automatically! Good luck!!!
They have already answered how to use a global variable.
I will tell you why the use of global variables is a bad idea as a result of this question carried out in stackoverflow in Spanish.
Explicit translation of the text in Spanish:
Impact of the change
The problem with global variables is that they create hidden dependencies. When it comes to large applications, you yourself do not know / remember / you are clear about the objects you have and their relationships.
So, you can not have a clear notion of how many objects your global variable is using. And if you want to change something of the global variable, for example, the meaning of each of its possible values, or its type? How many classes or compilation units will that change affect? If the amount is small, it may be worth making the change. If the impact will be great, it may be worth looking for another solution.
But what is the impact? Because a global variable can be used anywhere in the code, it can be very difficult to measure it.
In addition, always try to have a variable with the shortest possible life time, so that the amount of code that makes use of that variable is the minimum possible, and thus better understand its purpose, and who modifies it.
A global variable lasts for the duration of the program, and therefore, anyone can use the variable, either to read it, or even worse, to change its value, making it more difficult to know what value the variable will have at any given program point. .
Order of destruction
Another problem is the order of destruction. Variables are always destroyed in reverse order of their creation, whether they are local or global / static variables (an exception is the primitive types, int,enums, etc., which are never destroyed if they are global / static until they end the program).
The problem is that it is difficult to know the order of construction of the global (or static) variables. In principle, it is indeterminate.
If all your global / static variables are in a single compilation unit (that is, you only have a .cpp), then the order of construction is the same as the writing one (that is, variables defined before, are built before).
But if you have more than one .cpp each with its own global / static variables, the global construction order is indeterminate. Of course, the order in each compilation unit (each .cpp) in particular, is respected: if the global variableA is defined before B,A will be built before B, but It is possible that between A andB variables of other .cpp are initialized. For example, if you have three units with the following global / static variables:
Image1
In the executable it could be created in this order (or in any other order as long as the relative order is respected within each .cpp):
Image2
Why is this important? Because if there are relations between different static global objects, for example, that some use others in their destructors, perhaps, in the destructor of a global variable, you use another global object from another compilation unit that turns out to be already destroyed ( have been built later).
Hidden dependencies and * test cases *
I tried to find the source that I will use in this example, but I can not find it (anyway, it was to exemplify the use of singletons, although the example is applicable to global and static variables). Hidden dependencies also create new problems related to controlling the behavior of an object, if it depends on the state of a global variable.
Imagine you have a payment system, and you want to test it to see how it works, since you need to make changes, and the code is from another person (or yours, but from a few years ago). You open a new main, and you call the corresponding function of your global object that provides a bank payment service with a card, and it turns out that you enter your data and they charge you. How, in a simple test, have I used a production version? How can I do a simple payment test?
After asking other co-workers, it turns out that you have to "mark true", a global bool that indicates whether we are in test mode or not, before beginning the collection process. Your object that provides the payment service depends on another object that provides the mode of payment, and that dependency occurs in an invisible way for the programmer.
In other words, the global variables (or singletones), make it impossible to pass to "test mode", since global variables can not be replaced by "testing" instances (unless you modify the code where said code is created or defined). global variable, but we assume that the tests are done without modifying the mother code).
Solution
This is solved by means of what is called * dependency injection *, which consists in passing as a parameter all the dependencies that an object needs in its constructor or in the corresponding method. In this way, the programmer ** sees ** what has to happen to him, since he has to write it in code, making the developers gain a lot of time.
If there are too many global objects, and there are too many parameters in the functions that need them, you can always group your "global objects" into a class, style * factory *, that builds and returns the instance of the "global object" (simulated) that you want , passing the factory as a parameter to the objects that need the global object as dependence.
If you pass to test mode, you can always create a testing factory (which returns different versions of the same objects), and pass it as a parameter without having to modify the target class.
But is it always bad?
Not necessarily, there may be good uses for global variables. For example, constant values (the PI value). Being a constant value, there is no risk of not knowing its value at a given point in the program by any type of modification from another module. In addition, constant values tend to be primitive and are unlikely to change their definition.
It is more convenient, in this case, to use global variables to avoid having to pass the variables as parameters, simplifying the signatures of the functions.
Another can be non-intrusive "global" services, such as a logging class (saving what happens in a file, which is usually optional and configurable in a program, and therefore does not affect the application's nuclear behavior), or std :: cout,std :: cin or std :: cerr, which are also global objects.
Any other thing, even if its life time coincides almost with that of the program, always pass it as a parameter. Even the variable could be global in a module, only in it without any other having access, but that, in any case, the dependencies are always present as parameters.
Answer by: Peregring-lk
Is there a good way to allow only a certain class to have read/write access to properties in another class without having inheritance structure between them during design mode in .NET?
So if a class has public properties, only a certain class has visibility to these properties?
If not possible during design mode, then during run time. I know of a hokey way using flags in set and get statements but I think there are better ways.
There is no friend access in C#. You have public/protected/internal (including [InternalsVisibleTo]), but nothing more granular (i.e. at the inter-type level). So, no.
You can implement this using the internal keyword in C#:
The internal keyword is an access
modifier for types and type members.
Internal types or members are
accessible only within files in the
same assembly, as in this example:
public class BaseClass
{
// Only accessible within the same assembly
internal static int x = 0;
}
See also: Practical usings of “internal” keyword in C#
If you make the properties public anyone can access them. If you make them internal, protected, or even private --- anyone can still access them using reflection. If you want to discourage their use, use internal like Mitch suggested.
If there is a security reason for having this constraint, use Code Access Security to protect your properties. Note that this isn't something simple you can throw together -- thought must be put into your security model and the permissions you expose. Also realize that this must be done on an assembly level and will affect deployment of your application.
Chances are you probably don't need to do something so deep. You can probably "discourage" people from accessing those properties by hiding them behind an explicitly-implemented interface.
Could you please explain what the practical usage is for the internal keyword in C#?
I know that the internal modifier limits access to the current assembly, but when and in which circumstance should I use it?
Utility or helper classes/methods that you would like to access from many other classes within the same assembly, but that you want to ensure code in other assemblies can't access.
From MSDN (via archive.org):
A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.
You can also use the internal modifier along with the InternalsVisibleTo assembly level attribute to create "friend" assemblies that are granted special access to the target assembly internal classes.
This can be useful for creation of unit testing assemblies that are then allowed to call internal members of the assembly to be tested. Of course no other assemblies are granted this level of access, so when you release your system, encapsulation is maintained.
If Bob needs BigImportantClass then Bob needs to get the people who own project A to sign up to guarantee that BigImportantClass will be written to meet his needs, tested to ensure that it meets his needs, is documented as meeting his needs, and that a process will be put in place to ensure that it will never be changed so as to no longer meet his needs.
If a class is internal then it doesn't have to go through that process, which saves budget for Project A that they can spend on other things.
The point of internal is not that it makes life difficult for Bob. It's that it allows you to control what expensive promises Project A is making about features, lifetime, compatibility, and so on.
Another reason to use internal is if you obfuscate your binaries. The obfuscator knows that it's safe to scramble the class name of any internal classes, while the name of public classes can't be scrambled, because that could break existing references.
If you are writing a DLL that encapsulates a ton of complex functionality into a simple public API, then “internal” is used on the class members which are not to be exposed publicly.
Hiding complexity (a.k.a. encapsulation) is the chief concept of quality software engineering.
The internal keyword is heavily used when you are building a wrapper over non-managed code.
When you have a C/C++ based library that you want to DllImport you can import these functions as static functions of a class, and make they internal, so your user only have access to your wrapper and not the original API so it can't mess with anything. The functions being static you can use they everywhere in the assembly, for the multiple wrapper classes you need.
You can take a look at Mono.Cairo, it's a wrapper around cairo library that uses this approach.
Being driven by "use as strict modifier as you can" rule I use internal everywhere I need to access, say, method from another class until I explicitly need to access it from another assembly.
As assembly interface is usually more narrow than sum of its classes interfaces, there are quite many places I use it.
I find internal to be far overused. you really should not be exposing certain functionailty only to certain classes that you would not to other consumers.
This in my opinion breaks the interface, breaks the abstraction. This is not to say it should never be used, but a better solution is to refactor to a different class or to be used in a different way if possible. However, this may not be always possible.
The reasons it can cause issues is that another developer may be charged with building another class in the same assembly that yours is. Having internals lessens the clarity of the abstraction, and can cause problems if being misused. It would be the same issue as if you made it public. The other class that is being built by the other developer is still a consumer, just like any external class. Class abstraction and encapsulation isnt just for protection for/from external classes, but for any and all classes.
Another problem is that a lot of developers will think they may need to use it elsewhere in the assembly and mark it as internal anyways, even though they dont need it at the time. Another developer then may think its there for the taking. Typically you want to mark private until you have a definative need.
But some of this can be subjective, and I am not saying it should never be used. Just use when needed.
This example contains two files: Assembly1.cs and Assembly2.cs. The first file contains an internal base class, BaseClass. In the second file, an attempt to instantiate BaseClass will produce an error.
// Assembly1.cs
// compile with: /target:library
internal class BaseClass
{
public static int intM = 0;
}
// Assembly1_a.cs
// compile with: /reference:Assembly1.dll
class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // CS0122
}
}
In this example, use the same files you used in example 1, and change the accessibility level of BaseClass to public. Also change the accessibility level of the member IntM to internal. In this case, you can instantiate the class, but you cannot access the internal member.
// Assembly2.cs
// compile with: /target:library
public class BaseClass
{
internal static int intM = 0;
}
// Assembly2_a.cs
// compile with: /reference:Assembly1.dll
public class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // Ok.
BaseClass.intM = 444; // CS0117
}
}
source: http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx
Saw an interesting one the other day, maybe week, on a blog that I can't remember. Basically I can't take credit for this but I thought it might have some useful application.
Say you wanted an abstract class to be seen by another assembly but you don't want someone to be able to inherit from it. Sealed won't work because it's abstract for a reason, other classes in that assembly do inherit from it. Private won't work because you might want to declare a Parent class somewhere in the other assembly.
namespace Base.Assembly
{
public abstract class Parent
{
internal abstract void SomeMethod();
}
//This works just fine since it's in the same assembly.
public class ChildWithin : Parent
{
internal override void SomeMethod()
{
}
}
}
namespace Another.Assembly
{
//Kaboom, because you can't override an internal method
public class ChildOutside : Parent
{
}
public class Test
{
//Just fine
private Parent _parent;
public Test()
{
//Still fine
_parent = new ChildWithin();
}
}
}
As you can see, it effectively allows someone to use the Parent class without being able to inherit from.
When you have methods, classes, etc which need to be accessible within the scope of the current assembly and never outside it.
For example, a DAL may have an ORM but the objects should not be exposed to the business layer all interaction should be done through static methods and passing in the required paramters.
A very interesting use of internal - with internal member of course being limited only to the assembly in which it is declared - is getting "friend" functionality to some degree out of it. A friend member is something that is visible only to certain other assemblies outside of the assembly in which its declared. C# has no built in support for friend, however the CLR does.
You can use InternalsVisibleToAttribute to declare a friend assembly, and all references from within the friend assembly will treat the internal members of your declaring assembly as public within the scope of the friend assembly. A problem with this is that all internal members are visible; you cannot pick and choose.
A good use for InternalsVisibleTo is to expose various internal members to a unit test assembly thus eliminating the needs for complex reflection work arounds to test those members. All internal members being visible isn't so much of a problem, however taking this approach does muck up your class interfaces pretty heavily and can potentially ruin encapsulation within the declaring assembly.
As rule-of-thumb there are two kinds of members:
public surface: visible from an external assembly (public, protected, and internal protected):
caller is not trusted, so parameter validation, method documentation, etc. is needed.
private surface: not visible from an external assembly (private and internal, or internal classes):
caller is generally trusted, so parameter validation, method documentation, etc. may be omitted.
Noise reduction, the less types you expose the more simple your library is.
Tamper proofing / Security is another (although Reflection can win against it).
Internal classes enable you to limit the API of your assembly. This has benefits, like making your API simpler to understand.
Also, if a bug exists in your assembly, there is less of a chance of the fix introducing a breaking change. Without internal classes, you would have to assume that changing any class's public members would be a breaking change. With internal classes, you can assume that modifying their public members only breaks the internal API of the assembly (and any assemblies referenced in the InternalsVisibleTo attribute).
I like having encapsulation at the class level and at the assembly level. There are some who disagree with this, but it's nice to know that the functionality is available.
One use of the internal keyword is to limit access to concrete implementations from the user of your assembly.
If you have a factory or some other central location for constructing objects the user of your assembly need only deal with the public interface or abstract base class.
Also, internal constructors allow you to control where and when an otherwise public class is instantiated.
I have a project which uses LINQ-to-SQL for the data back-end. I have two main namespaces: Biz and Data. The LINQ data model lives in Data and is marked "internal"; the Biz namespace has public classes which wrap around the LINQ data classes.
So there's Data.Client, and Biz.Client; the latter exposes all relevant properties of the data object, e.g.:
private Data.Client _client;
public int Id { get { return _client.Id; } set { _client.Id = value; } }
The Biz objects have a private constructor (to force the use of factory methods), and an internal constructor which looks like this:
internal Client(Data.Client client) {
this._client = client;
}
That can be used by any of the business classes in the library, but the front-end (UI) has no way of directly accessing the data model, ensuring that the business layer always acts as an intermediary.
This is the first time I've really used internal much, and it's proving quite useful.
There are cases when it makes sense to make members of classes internal. One example could be if you want to control how the classes are instantiated; let's say you provide some sort of factory for creating instances of the class. You can make the constructor internal, so that the factory (that resides in the same assembly) can create instances of the class, but code outside of that assembly can't.
However, I can't see any point with making classes or members internal without specific reasons, just as little as it makes sense to make them public, or private without specific reasons.
the only thing i have ever used the internal keyword on is the license-checking code in my product ;-)
How about this one: typically it is recommended that you do not expose a List object to external users of an assembly, rather expose an IEnumerable. But it is lot easier to use a List object inside the assembly, because you get the array syntax, and all other List methods. So, I typically have a internal property exposing a List to be used inside the assembly.
Comments are welcome about this approach.
Keep in mind that any class defined as public will automatically show up in the intellisense when someone looks at your project namespace. From an API perspective, it is important to only show users of your project the classes that they can use. Use the internal keyword to hide things they shouldn't see.
If your Big_Important_Class for Project A is intended for use outside your project, then you should not mark it internal.
However, in many projects, you'll often have classes that are really only intended for use inside a project. For example, you may have a class that holds the arguments to a parameterized thread invocation. In these cases, you should mark them as internal if for no other reason than to protect yourself from an unintended API change down the road.
The idea is that when you are designing a library only the classes that are intended for use from outside (by clients of your library) should be public. This way you can hide classes that
Are likely to change in future releases (if they were public you would break client code)
Are useless to the client and may cause confusion
Are not safe (so improper use could break your library pretty badly)
etc.
If you are developing inhouse solutions than using internal elements is not that important I guess, because usually the clients will have constant contact with you and/or access to the code. They are fairly critical for library developers though.
When you have classes or methods which don't fit cleanly into the Object-Oriented Paradigm, which do dangerous stuff, which need to be called from other classes and methods under your control, and which you don't want to let anyone else use.
public class DangerousClass {
public void SafeMethod() { }
internal void UpdateGlobalStateInSomeBizarreWay() { }
}