Many const integers in a program [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am a C# junior programmer and running into a requirement of defining a lot of constant integers in my program (up to 5000 of them). I would like to know whether doing something like this in my C# program file
const int a=1;
const int b=2;
....
const int x5000=5000;
is practical in a business application. My supervisor tells me to leave them in a separate file then initialize a variable to store them when the program starts to run. But I find that method is no good because any user can change the file.
I don't know if there is any better way to do this. I also think all of constant things are still apparent in a compiled C# file even when I view it with notepad. I would want all of the readable text in source files after compiled into a pe to be hexificated.

A common method of handling this is to declare classes that holds your constant values and gives them meaningful names.
With thousands of constants it may be useful to use more than one class if the constants can be grouped meaningfully, usually around how they are used.
public class Constants
{
public int A { return 1; }
public int B { return 2; }
public int X5000 { return x5000; }
}
These classes are then passed into any class that needs the constants they hold.
Additionally, if desired, the class can be initialized with the values from an external source during construction.
The main point is to give the constants meaningful names, group by use and abstract away where the values are coming from.

In such cases I'm trying to gather consts into logical groups. Each group - one class:
public sealed class ABCConsts{
public const int A=1;
public const int B=2;
...
}
...
public sealed class XConst{
public const int X5000 = 5000;
}
it's better to put each class into separate file.
PS: good stuf to futher reading - Static readonly vs const fields

You may take a look at enum
and add a static class, something like ErrorCodeManager to access the enum, just in cause of refactoring source of those error code
public static class Constants
{
public static int A { get { return 1; } }
public static int B { get { return 2; } }
public static int C { get { return 3; } }
public static int x5000 { get { return 5000; } }
}
public enum EConst
{
A = 1,
B, // <= value is 2
C, // <= value is 3
x5000 = 5000,
}
They both work the same way,in my opinion enum is even more readable, why using static int?

Related

Multi-methods with multi-parameters or one method with object parameter [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Consider the following; I have a class with X and Y variables. the Idea of class is to change the position of points in both X axis and Y axis . I made a three methods in the first place for this purpose as :
the first one is to chage to X position
the second to change the Y position
the third one is to change both X and Y by passing on object for this class
The Code as
public class ChangePosition
{
public int X_AxisPosition;
public int Y_AxisPosition;
public ChangePosition(int X_Axis,int Y_Axis)
{
this.X_AxisPosition = X_Axis;
this.Y_AxisPosition = Y_Axis;
}
public void ChangeXAxisPosition(int XValue)
{
X_AxisPosition = XValue;
}
public void ChangeYAxisPosition(int YValue)
{
Y_AxisPosition = YValue;
}
public void ChangeXAxis_YAxisValues(ChangePosition NewLocaltion)
{
if (NewLocaltion == null)
{
X_AxisPosition = default;
Y_AxisPosition = default;
throw new NullReferenceException("Invalid Inputs");
}
ChangeXAxisPosition(NewLocaltion.X_AxisPosition);
}
}
After a while i rethinking and said why do i have two method in above (For Only either Axles), I could have the last one by passing on object form this class and set the unneeded Axis to zero as the following block showing U
public class ChangePosition
{
public int X_AxisPosition;
public int Y_AxisPosition;
public ChangePosition(int XValue, int YValue)
{
X_AxisPosition = XValue;
Y_AxisPosition = YValue;
}
public void ChangeXAxis_YAxisValues(ChangePosition NewLocaltion)
{
if (NewLocaltion == null)
{
throw new NullReferenceException("Invalid Inputs");
}
X_AxisPosition =(NewLocaltion.X_AxisPosition);
Y_AxisPosition =(NewLocaltion.Y_AxisPosition);
}
}
Could someone told me in term of best practices which of the previous code block is better? and Why?
The best practice for such entities as "position" or "vector" is to make them immutable - because its identity depends only on its state. It means that two ChangePosition objects, initialized with same X_AxisPosition and Y_AxisPosition are equal. So, whenever you want to change a field of immutable enitity, you always can simply replace the whole object. The fact that two points with the same state may be considered as different entities in your code may lead you into troubles.
In your case, public void ChangeXAxis_YAxisValues(ChangePosition NewLocaltion) doesn't make sense, since whenever you could use it like
someObject.Position.ChangeXAxis_YAxisValues(new ChangePosition(x, y));
you should better write
someObject.Position = new ChangePosition(x, y);
A common practice for points/positions is to use struct, struct is actually mutable, but its identity is represented with its state (struct's with same values of fields are equal, but not classes). It is also good to make its fields readonly, if it doesn't slow performance significantly.
So, keep it simple:
public struct ChangePosition
{
public int X_AxisPosition;
public int Y_AxisPosition;
public ChangePosition(int X_Axis,int Y_Axis)
{
this.X_AxisPosition = X_Axis;
this.Y_AxisPosition = Y_Axis;
}
}
Also, normally you may find useful to implement + operator.

Different ways to declare properties [duplicate]

This question already has answers here:
C# 3.0 auto-properties — useful or not? [closed]
(17 answers)
What is the difference between a field and a property?
(33 answers)
Closed 7 years ago.
Excuse me if my question is pretty much about code-style, but for simple cases which of the bellow is better?
CASE 1:
private static int number = 1;
public static int Number
{
get { return number; }
set { number = value; }
}
CASE 2:
public static int Number
{
get;
set;
}
I think case 2 is better because, when you have many properties in your class they won't consume so much space and the filesize will be reduced.
The syntax below is called auto properties, it doesn't matter in the terms of file size since in compilation time, a field is generated anyway (see, decompilation in the end of the answer) and there are get and set methods in the compilation results in both cases.
Auto properties allow you to keep your code more organized and short which is good for your code maintainability and readability, therefore you should prefer them when possible.
We will put aside the "In field without auto-property you can assign default value" topic for a second (also, it is possible now in auto-properties too in c# 6.0), sometimes, you want to run some more code inside the get or set methods of the property, like invoking event handles or validating the values, that's where standard property declaration comes into the picture, for example:
private int mNumber;
public int Number
{
get
{
return Number;
}
set
{
if (Number == 8)
{
throw new CannotReceive8Exception();
}
else
{
mNumber = value;
}
}
}
If you look at the decompiled code of this code:
public int Number { get; set; }
You will see that the compiler has added a background private field anyway:
While there is no difference to the compiler, since it would generate the fields for you, I prefer to leave my code clean and just use
public int Num {get;set;}
in one line, since there is no supreme meaning to explicitly typing the code and keeping it in one line allows me to differentiate properties like this from methods, which span across multiple lines at glance.

Creating data members of a class in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am a beginner programmer looking for some help with c#.
I am writing a program based on a framework and need to create a data member of a class, then initialize the data member to something.
Next,I need to make a property to get and set the data member.
Also, if someone could provide some information on how to typecast the property that would be great.
I'm just looking for examples and general information here. I checked google and only got links from MSDN but did not understand the content.
Thanks!
Here is a basic explanation, using code:
//Class Definition
public class MyClass
{
//Data Member with inline initialization
private int myInt = 1;
//Standard property
public int MyIntProp
{
get { return myInt; }
set { myInt = value; }
}
//Auto-property, generates the same getter/setter as above with a "hidden" backing property.
public String MyStringProp {get; set;}
//Class constructor, great for initialization!
public MyClass()
{
//Set the property to an initial value
MyStringProp = "Hello World";
}
}
Typecasting is another monster. You have to be careful when doing it, because very few types can be cast to others. The number types can generally be cast to one another (although you can lose data), and derived types can be cast to their base types, but that is about it.
An example (safe) cast of a number would be:
int myInt = 2;
long myLong = (long)myInt;
That is called a "C-Style" cast (because it's how you do it in C) and is generally how you cast numbers. There are other styles and functions to do the cast of course.
#Iahsrah's suggestion is also a good place to start.
A basic type is a class which looks like this:
public class MyType
{
}
You can create a property of this on another class like this:
public class AnotherType
{
public MyType InlinePropertyName { get; set; }
// Simple propertoes require no implimentation (above), or you can explicitly control it all (below)
private MyType _explicitPropertyName;
public MyType ExplicitPropertyName {
get {
return _explicitPropertyName;
}
set {
_explicitPropertyName = value;
}
}
}
The you can easily access from elsewhere in your program like this:
var myType = new MyType();
var anotherType = new AnotherType();
anotherType.InlinePropertyName = myType;

Is there an equivalent of 'this' in C# for static members?

Is there an equivalent of this in C# for static members?
I like to use this to make my code more readable, but wondered if there was an equivalent for static members.
I suppose if you use this. to reinforce that you are referring to instance members, the equivalent in a static member would be to use ClassName.
But stylistically, why add code that doesn't change meaning?
edit to add various clarifications:
My last sentence above can be illustrated with these examples:
class Example1
{
public int J { get; set; }
public Example1()
{
J = 0;
}
// These two methods have *exactly* the same CIL
public int InstanceMethodLong()
{
return this.J;
}
public int InstanceMethodShort()
{
return J;
}
}
The this. in InstanceMethodLong does not change the meaning as compared with InstanceMethodShort.
Statically:
class Example2
{
public static int K { get; set; }
static Example2()
{
K = 0;
}
// These two methods have *exactly* the same CIL
public int StaticMethodLong()
{
return Example2.K;
}
public int StaticMethodShort()
{
return K;
}
The Example2. in StaticMethodLong does not change the meaning as compared with StaticMethodShort.
In both these cases, adding the qualifier results in the same CIL, the same behaviour, and is more source to write, read, and understand. Stylistically - and I will happily accept that this is a question of code style - I see no reason for it to be there.
With underscore prefixes the situation is slightly different:
class Example3
{
int _j;
public int J
{
get { return _j; }
set
{
_j = value;
// and do something else,
// to justify not using an auto-property
}
}
public Example3()
{
J = 0;
}
public int MethodWithParameter(int j)
{
// Now there is a *difference* between
return j;
// and
return _j;
}
}
Here, in MethodWithParameter, there is a difference between referring to _j and j - so we are deliberately and explicitly expressing different meaning. It's true that the compiler doesn't care what we call our variable names, but it does care what variables we are referring to! So in the body of MethodWithParameter, using or not using an underscore isn't just stylistic, it's semantic. Which isn't the particular issue we're addressing in this question.
As a static member is not meant to belong to any particular instance (as this refers to an instance of an object, with different settings possible per instance), what you would instead want to do is use ClassName.Member instead of this.Member.
public class Orange
{
public static string Tastes = "sweet";
public static string FoodType(){
return "fruit";
}
}
Would be called by:
Console.WriteLine(Orange.Tastes);
Same goes for static methods, as well:
Console.WriteLine(Orange.FoodType()).
Please note this is a contrived example for demonstration only. :)
You may able to use the class name to reference other static properties.
Your code becomes a bit more resistant to copy/paste but that's not always a bad thing.
Unfortunately no, there is no this for static methods. To help differentiate static members from class members I prefix it with the class name.
class Test {
static Regex TextRegex = new Regex(...);
public static bool TestString(string input) {
return Test.TextRegex.IsMatch(input);
}
}
I like "this" as well to realsie from the first look where the state is changing. You may want to consider type's name for static members in this case.

How do I get data from public interface to use? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
There is a public interface in the project with a value as follows:
Name3D MyName3D { get; set; }
Now in another location I am using a public sealed class, I added the namespace / using System.Interfacename. Now I want to set it like follows:
private readonly Interfacename m_MyName3D ;
private const string 3DName = ##;
How would i go aobut setting it up so ## is the value of MyName3D. Again I haven't done anything like this before. Just wanted to give it a try?
Would be really appreciated if I could get some detail onto how it works.
Update One
Do you mean this?
using Interfacename;
public sealed class InfoController : AsyncController
{
private readonly Interfacename m_MyName3D ;
private const string 3DName = ##;
You can not assign anything to a const member at runtime. You can however make 3DName a readonly property and relay the get accessor to the interface:
private string 3DName { get { return m_MyName3D.MyName3D; } }
But maybe I did not get what you are trying to do, if so please describe it more clearly.
edit: you are using two types for 3DName, Name3D and string. If Name3D has no conversion operators you need to use it throughout the property.
private Name3D 3DName { get { return m_MyName3D.MyName3D; } }
If you really need to return a string the you need to write a string conversion operator for Name3D:
struct/class Name3D
{
public static implicit operator string(Name3D name)
{
return name.whatever; // this needs to be the data holding member(s) of Name3D
}
}

Categories