Is there anyway to #define CONSTANT on a solution basis?
You can actually use a variation on Ritch's approach with common project settings. Essentially you have to make a single change to the end of each project file in your solution:
<PropertyGroup Condition="'$(SolutionDir)' == '' or
'$(SolutionDir)' == '*undefined*'">
<SolutionDir>..\..\</SolutionDir>
</PropertyGroup>
<Import Project="$(SolutionDir)CommonSettings.targets" />
</Project>
Then you can define CommonSettings.targets to contain the solution wide settings.
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
ToolsVersion="3.5">
<PropertyGroup>
<TacoBuild>true</TacoBuild>
</PropertyGroup>
</Project>
That's basically it unless you want to override or merge project settings already defined in each project. The link below discusses how to do this in some detail.
http://www.ademiller.com/blogs/tech/2007/12/common-project-settings-for-your-visual-studio-solution/
What is the best way to implement constants in Java?
That is perfectly acceptable, probably even the standard.
(public/private) static final TYPE NAME = VALUE;
where TYPE
is the type, NAME
is the name in all caps with underscores for spaces, and VALUE
is the constant value;
I highly recommend NOT putting your constants in their own classes or interfaces.
As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.
For example:
public static final Point ORIGIN = new Point(0,0);
public static void main(String[] args){
ORIGIN.x = 3;
}
That is legal and ORIGIN
would then be a point at (3, 0).
Solution-wide #define
Update: You cannot do a "solution-wide" define afaik, however the answer below is workable on a per-project basis.
You set them in your Compilation Properties or Build options:
http://msdn.microsoft.com/en-US/library/76zdzba1(v=VS.80).aspx (VS2008)
http://msdn.microsoft.com/en-US/library/76zdzba1(v=VS.100).aspx (VS2010)
see the "To set a custom constant" heading.
Update
Microsoft Documentation on Build Options
You get to the build options by right-clicking the project and selecting properties from the menu.
Can I #define a constant solutionwide within c# code without project settings?
After a lot of searches I've finally been able to put together a surprisingly simple solution I'ld like to share with you:
InitializeOnLoad
Unity has an attribute [InitializeOnLoad]
. It tells Unity to initialize according class as soon as
- Unity is launched
- After any re-compiling of scripts => also after importing a new unitypackage with scripts
static Constructor
In their Running Editor Code On Launch example, they show, how to combine this with a static
constructor.
From static-constructors:
A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
While usually you still would have to create an instance of the class, the static constructor is "instanciated/executed" instantly when the class is initliazed, which we force using the [InitializeOnLoad]
attribute.
Scripting Define Symbols
Further Unity actually has project wide defines in the PlayerSettings
.
And the good part is: We also have access to them via scripting API:
PlayerSettings.GetScriptingDefineSymbolsForGroup
PlayerSettings.SetScriptingDefineSymbolsForGroup
.
So what I did now is the following
Module A
This module has no dependencies but just defines a "global define" in the PlayerSettings. I placed this script somewhere e.g. in Assets/ModuleA/Editor
(important is the last folder's name).
using System.Linq;
using UnityEditor;
namespace ModuleA
{
// Will be initialized on load or recompiling
[InitializeOnLoad]
public static class Startup
{
// static constructor is called as soon as class is initialized
static Startup()
{
#region Add Compiler Define
// Get the current defines
// returns a string like "DEFINE_1;DEFINE_2;DEFINE_3"
var defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
// split into list just to check if my define is already there
var define = defines.Split(';').ToList();
if (!define.Contains("MODULE_A")
{
// if not there already add my define
defines += ";MODULE_A";
}
// and write back the new defines
PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, defines);
#endregion
}
}
}
Module B
This module depends on Module A
. So itself defines a "global define" (so later Modules can check their dependecies on Module B
) but additionally it checks first, if Module A is imported. If Module A
is missing, it prints an error to the Debug Console.
(You could as well throw a compiler error using #error SOME TEXT
, but for some reason this is not capable of printing out the URL correctly so I decided for the Debug.LogError
)
I placed this script somewhere e.g. in Assets/ModuleB/Editor
#if MODULE_A
using System.Linq;
#endif
using UnityEditor;
#if !MODULE_A
using UnityEngine;
#endif
namespace ModuleB
{
// Will be initialized on load or recompiling
[InitializeOnLoad]
public static class Startup
{
// static constructor is called as soon as class is initialized
static Startup()
{
#if !MODULE_A
Debug.LogErrorFormat("! Missing Module Dependency !" +
"\nThe module {0} depends on the module {1}." +
"\n\nDownload it from {2} \n",
"MODULE_B",
"MODULE_A",
"https://Some.page.where./to.find.it/MyModules/ModuleA.unitypackage"
);
#else
// Add Compiler Define
var defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
var define = defines.Split(';').ToList();
if (!define.Contains("MODULE_B"))
{
defines += ";MODULE_B";
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, defines);
#endif
}
}
}
So later in other scripts of Module B I have two options (both do basically the same)
I can either check everywhere
#if MODULE_A
to check exactly the module this script relies onor I can instead check
#if MODULE_B
to rather check with one line if all dependecies are fulfilled since otherwise I don't defineMODULE_B
.
On this way I can completely check all dependencies between certain modules which is awesome. The only two flaws I saw until now are:
- We have to know how the define (e.g.
MODULE_A
) looks like for every module and if it is changed in the future it has to be changed in all depending modules as well - The "global define" isn't getting removed in case the module is deleted from the project
But well - which solution is perfect?
Polymer: How to define constant variables on a per-file basis?
For constants that differ between files, just use a private property by prefixing with _
. For constants that need shared, you could do the same thing but in a behavior in a separate file that can be imported into any file that needs those constants.
properties: {
_requestUrl: {
type: String,
value: '/test'
}
}
For behavior do the same thing but treat as behavior. https://www.polymer-project.org/1.0/docs/devguide/behaviors
How do I create a constant in Python?
You cannot declare a variable or value as constant in Python.
To indicate to programmers that a variable is a constant, one usually writes it in upper case:
CONST_NAME = "Name"
To raise exceptions when constants are changed, see Constants in Python by Alex Martelli. Note that this is not commonly used in practice.
As of Python 3.8, there's a typing.Final
variable annotation that will tell static type checkers (like mypy) that your variable shouldn't be reassigned. This is the closest equivalent to Java's final
. However, it does not actually prevent reassignment:
from typing import Final
a: Final[int] = 1
# Executes fine, but mypy will report an error if you run mypy on this:
a = 2
What is the correct way to define a constant value in a derived class used to validate parameters in a parent constructor in C#
After re-reading Peter Duniho's comments I came up with this refactoring which I believe is a much better solution. (I think the wording of the question was a little ambiguous/subjective because the logic was off initially and I was looking for a correction to my logic as opposed to knowing exactly what the problem was and how to fix that problem)
The question:
What is the correct way to define a constant value in a derived class
used to validate parameters in a parent constructor in C#
Short answer, you don't. Defining a constant in the above sample code is not necessary. It doesn't need to be stored at all, it is not something that other parts of the code (in this case) need, it is a value that is only needed for validation upon instantiation.
public class Triangle: Polygon
{
public Triangle(Point2D[] vertices) : base(vertices, 3){}
}
public class Quadrilateral: Polygon
{
public Quadrilateral(Point2D[] vertices) : base(vertices, 4){}
}
The other goal that I was trying to accomplish (with the original example), was early validation. In other words, if the correct number of vertices is not passed for the derived type, I want to stop initialization before any other initialization steps are performed on an invalid object. In the given example, an empty default constructor and validation within the derived constructor (or even a call to a validation method contained in the base method from the derived constructor) would be fine, not passing the vertices to the base, rather validating and then setting them in the derived constructor. However, the key is early validation, what if the base class does a bunch of stuff (a more complex class) to (pre)initialize the object before getting to the derived class. Validation code really belongs before any processing (including initialization).
By passing a (validation related) value to the base constructor allows the validation to occur at the beginning, so as to prevent other code from running if the validation fails.
protected Polygon(Point2D[] vertices, int expectedVerticesCount)
{
// Don't bother initializing the object, the data is invalid!
if(vertices.Length != expectedVerticesCount)
throw new ArgumentOutOfRangeException( /* ... */);
// The data is valid, proceed with initialization
Vertices = vertices;
}
Can I force a subclass to declare a constant?
No, you can't. I would suggest you make your base class abstract, with an abstract property which you can fetch when you want. Each child class can then implement the property just by returning a constant if it wants. The downside is that you can't use this within static methods in the base class - but those aren't associated with the child classes anyway.
(It also allows child classes to customise the property per instance as well, if necessary... but that's rarely an actual problem.)
If this doesn't do enough for you, you might want to consider a parallel type hierarchy. Basically polymorphism simply doesn't happen in a type-specific way in .NET; only in an instance-specific way.
If you still want to do this and fetch it with reflection, I suggest you just write unit tests to ensure that the relevant constants are defined. When you get beyond what the type system can describe, that's often the best you can do.
Define constant variables in C++ header
You could simply define a series of const ints
in a header file:
// Constants.h
#if !defined(MYLIB_CONSTANTS_H)
#define MYLIB_CONSTANTS_H 1
const int a = 100;
const int b = 0x7f;
#endif
This works because in C++ a name at namespace scope (including the global namespace) that is explicitly declared const and not explicitly declared extern has internal linkage, so these variables would not cause duplicate symbols when you link together translation units. Alternatively you could explicitly declare the constants as static.
static const int a = 100;
static const int b = 0x7f;
This is more compatible with C and more readable for people that may not be familiar with C++ linkage rules.
If all the constants are ints then another method you could use is to declare the identifiers as enums.
enum mylib_constants {
a = 100;
b = 0x7f;
};
All of these methods use only a header and allow the declared names to be used as compile time constants. Using extern const int
and a separate implementation file prevents the names from being used as compile time constants.
Note that the rule that makes certain constants implicitly internal linkage does apply to pointers, exactly like constants of other types. The tricky thing though is that marking a pointer as const
requires syntax a little different that most people use to make variables of other types const. You need to do:
int * const ptr;
to make a constant pointer, so that the rule will apply to it.
Also note that this is one reason I prefer to consistently put const
after the type: int const
instead of const int
. I also put the *
next to the variable: i.e. int *ptr;
instead of int* ptr;
(compare also this discussion).
I like to do these sorts of things because they reflect the general case of how C++ really works. The alternatives (const int
, int* p
) are just special cased to make some simple things more readable. The problem is that when you step out of those simple cases, the special cased alternatives become actively misleading.
So although the earlier examples show the common usage of const
, I would actually recommend people write them like this:
int const a = 100;
int const b = 0x7f;
and
static int const a = 100;
static int const b = 0x7f;
How to define constants for use with With[] in one place and then apply them later?
What I'd do is to write a function generator to create custom (lexical) environments:
ClearAll[makeCustomEnvironment];
SetAttributes[makeCustomEnvironment, HoldAll];
makeCustomEnvironment[values : (_Symbol = _) ..] :=
Function[code, With @@ Hold[{values}, code], HoldAll];
This takes a declaration list and creates a pure function which uses With
internally with encapsulated constants. I used With@@Hold[...]
to fool the renaming mechanism of Function
so that it would not rename the variables inside With
(instead of With
, one could use the withRules
function suggested by @Szabolcs, which would lead to a slightly different substitution semantics).
Now, we create our custom function:
env = makeCustomEnvironment[$age = 2, $salary = 3];
And use it like so:
In[25]:=
env[x=$age];
x
Out[26]= 2
In[27]:=
env[y=$age];
y
Out[28]= 2
The advantage of this construct with respect to a saved variable (with rules or whatever) is that here we encapsulate behavior rather than state. This is arguably cleaner and more along the functional programming paradigm (we create here a closure rather than instantiate a class).
EDIT
Apparently, the rules for demonstrations are pretty strict, and won't allow the sugested code. This version will hopefully be ok:
makeCustomEnvironmentAlt =
Function[Null,
Function[code, With @@ Hold[{##}, code], HoldAll],
HoldAll]
But you'll have to remember the format of input arguments (which was clear for the initial solution due to the use of suggestive pattern).
Related Topics
C# Call C++ Dll Passing Pointer-To-Pointer Argument
How Get List of Local Network Computers
Interop.Word Documents.Open Is Null
.Net Decompiler for MAC or Linux
Non-Virtual Interface Design Pattern in C#/C++
How to Add a Reference to an Unmanaged C++ Project Called by a C# Project
JSON Serialize List<Keyvaluepair<String, Object>>
Are Get and Set Functions Popular with C++ Programmers
Insert Text into the Textbox of Another Application
How to Pass Current User Information to All Layers in Ddd
Sending a Value from Server to Client with Sockets
Use Decimal Values as Attribute Params in C#
Configure Multiple Database Entity Framework 6
How to Write My C++ Function So I Can Call It from C#
How to Display a Loading Control While a Process Is Waiting for Be Finished
How to Open PDF File in a New Tab or Window Instead of Downloading It (Using ASP.NET)