convert variable to constant - c#

Can seems to be strange, but is there a way to declare or convert variable to constante something like :
string myVariable = "MyString";
const string myConstant = myVariable ;
I need this to answer to my problem:
linq to sql startwith performance indexed columns
thanks

no there is no way to do this for Const Const values are burned directly into the call-site at compile time, Instead you could make it readonly and assign it in the constructor
something like
string myVariable = "MyString";
readonly string myConstant="test" ;
public MyClass()
{
myConstant= myVariable ;
}

No, you cannot initialize a constant using the value of a variable.
Constants must be known at compile time, and the value of a variable is not known until runtime, making it conceptually impossible.

Otherwise, change your first variable to a constant like below :
const string myVariable = "MyString";
const string myConstant = myVariable ;

No, you can't use a variable to initialize a field. The compiler may re-arrange the order these are initialized in, myConstant could be initialized first, in which case myVariable would be not be set.

Constants cannot vary because they are not variables setting it to a variable would be varying it. So the answer is no at least not at runtime.
Maybe you just want something that can't be set many places then readonly might work.
reference: http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
public readonly string _myROString = "set once";

Well is not possible. But someone find an answer to my initial question without constant. thanks
linq to sql startwith performance indexed columns

This answer does not provide solution to the question posted; But may satisfy the requirement for some viewers who like to access string in a static manner which should be appended with other strings,
public enum NameTypes
{
First, Last
}
public static class UserDetails
{
public static string NameText = "Name Info: " + NameTypes.First.ToString();
}

Related

can i use variable content in class/function names?

can i use variable content in class/function names?
for example:
string string_1 = "abcd";
double num_2 = 20.5;
int num = 1;
MessageBox.Show(string_{num}); // shows string_1;
[I'm newbie in Visual C# (visual studio 2008)]
Thanks.
No you can't. A class name is defined at compile time.
Class and method names must be constant and have to be referred to as constants in code like your example.
You can use reflection and/or the dynamic type for dynamic behaviour.
Definitely not.
Such semantic is not possible in any programing language as far as I know.
double num_2 = 20.5;
MessageBox.Show(GetName(() => num_2));
public string GetName<T>(Expression<Func<T>> f)
{
return (f.Body as MemberExpression).Member.Name;
}

Other equivalent to enum?

I like to use enum as value holders whereever possible and I like it. It is easy to use i.e. just put a dot and see values. It is a good replacement of hard code some time.
But still it has some limitations. We cannot put special characters in values and some other.
Actually I am trying to make code reusable. Please guide me. Is there some technique or way that I can use some data structure like enum that is flexible but have no limitations.
You could use constants; they are immutable and can have any value.
See also: http://msdn.microsoft.com/en-us/library/ms173119.aspx
If I cannot use an enum for a set of predefined values, I use a class of static constants. They look much the same in use, but the values can be anything from a decimal to a string to a struct or class. I've done this for predefined cell color schemes in GridViews, much like the built-in Color class has predefined constant values. Mathematical and scientific constants such as e and Pi (if you wanted different values than are provided by the Math class), or the acceleration of gravity (9.8m/s2), or the speed of light (299,792,458m/s), can also be specified in this way.
If you think you can't use Enums because you need to store predefined string values, try this handy trick using the System.ComponentModel Description attribute:
public Enum MyStrings
{
[Description("This is string one")] StringOne,
[Description("This is a different string")] StringTwo,
...
}
To get the strings out, you simply examine the Description attribute, the code for which is a little messy but can be easily hidden behind an extension method:
public static string GetDescription(this Enum enumValue)
{
object[] attr = enumValue.GetType().GetField(enumValue.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false);
return (attr.Length > 0)
? ((DescriptionAttribute) attr[0]).Description
: String.Empty;
}
Usage:
var stringOne = MyStrings.StringOne.GetDescription(); //"This is string one"
In this case, you can also consider using a Resource file. The value of the string can be changed from outside the scope of the program, without a recompile.
Not sure what exactly you need (re: "special characters"), but you could simply use some constants and put them into a static class, e.g:
public static class MyConstants
{
/// <summary>documentation here</summary>
public const string ValueA = "somevalue";
/// <summary>documentation here</summary>
public const string ValueB = "something else with special characters &#";
// etc.
}
Usage:
var x = MyConstants.ValueB;
One issue you might find with enums and more especially constants is that if you change the source assembly which defines the enum or constant, but don't recompile dependent assemblies, you'll end up mismatching in the source and dependent assemblies. For example:
public const int myConst = 5;
You later change this to:
public const int myConst = 10;
In the source assembly, which was rebuilt, it's 10. But it's 5 in any dependent assemblies that were not rebuilt.
To avoid this, use readonly instead of const. For example:
public readonly int myConst = 5;
This is different than a const, which is more like a C++ #define which causes the value to be placed directly in code. Readonly will cause a lookup at runtime, so if you don't recompile your dependent assemblies you'll still get the correct, updated value.

Why System.String beahaves like a value type? (How to write value type classes like string?)

I want to write a 'Date' class that behaves like a Value Type.
for example, Instead of writing a Clone method for setting properties safely, make the Date class to pass by value:
public Date Birthday
{
get { return this.birthday; }
set
{
this.birthday = value.Clone();
} //I want to write this.birthday = value;
//without changing external value when this.Birthday changes
}
I know this is possible because System.String is a class and behaves like a value. for example:
String s1 = "Hello";
String s2 = "Hi";
s1 = s2;
s2="Hello";
Console.WriteLine(s1); //Prints 'Hi'
First I thought writers of this class override '=' operator, but now I know that the '=' operator can not be overridden. so how they write String class?
Edit: I just want to make my Date class to pass it's instances by value, like as String.
First, your string-based example does not illustrate your question.
The thing with DateTime and String is that they are immutable: once an instance is created, it cannot be changed in any way. For example, you cannot add 2 minutes to a DateTime instance by just saying date.Minutes += 2: you'll have to invoke date.AddMinutes(2), which will yield a totally new instance.
To make objects read-only, just follow the same pattern.
public class Date{ ...code...} would be a reference type...not what you want.
public struct Date { ...code...} would be a value type...probably what you want.
The string class is, as it is a class, a reference type...and is immutable..how being immutable effects the behavior of string objects can be confusing at the start.
Given string s1 = "Fish"; s1 is a reference that points to "Fish"...It is the "Fish" bit can never be changed....what s1 points to can be changed. If you then assign s1 = "Tuna"; "Fish" still exists but is no longer referenced and will be GC'd.
In your example after: s1=s2 s1,s2 now reference the same string "Hi"...there is only one "Hi".
I hope I have not gone way below your level.
It's not the '=' operator, it's the fact that when you say
stringThing = "thing";
you're creating a new string, not changing the current string to something else.

C# enum to string auto-conversion?

Is it possible to have the compiler automatically convert my Enum values to strings so I can avoid explicitly calling the ToString method every time. Here's an example of what I'd like to do:
enum Rank { A, B, C }
Rank myRank = Rank.A;
string myString = Rank.A; // Error: Cannot implicitly convert type 'Rank' to 'string'
string myString2 = Rank.A.ToString(); // OK: but is extra work
No. An enum is its own type, so if you want to convert it to something else, you have to do some work.
However, depending on what you're doing with it, some methods will call ToString() on it automatically for you. For example, you can do:
Console.Writeline(Rank.A);
You are not probably looking for enums itself, but a list of string constant. It can fit your needs better in some scenarios.
Use this instead:
public static class Rank
{
public const string A = "A";
public const string B = "B";
public const string C = "C";
}
No, but at least you can do things with enums that will call their ToString() methods when you might need to use their string value, e.g.:
Console.WriteLine(Rank.A); //prints "A".
The correct syntax should be
myRank.ToString("F");
[Caution, hack] Unsure as to whether this is nasty, to me it seems a reasonable compromise.
var myEnumAsString = MyEnum+"";
Console.WriteLine(myEnumAsString); //MyEnum
This will force implicit ToString()

Assignment problem

ag = logss_EventAnalyzer.tabEventsString[0];
ag is a static string,
logss_EventAnalyzer is a class,
tabEventString is a static string array.
During debugging, I saw that logss_EventAnalyzer.tabEventsString[0] contains some string, but it is not assigning into ag. It's value is null.
What is the problem here and what is the solution ?
Thanks !
You say "during debugging"; does logss_EventAnalyzer.tabEventsString[0] contain a (non-null) string when you assign ag?
Note that the assignment doesn't mean that changes to tabEventsString[0] will be reflected in ag, since string is immutable, and any changes to tabEventsString[0] are actually creating new strings. If you want this type of behaviour, you'll need to use a member of some class:
public class Foo {
public string Bar {get;set;}
}
static Foo ag;
static Foo[] tabEventsString;
...
ag = logss_EventAnalyzer.tabEventsString[0];
...
now ag.Bar will always be the same as tabEventsString[0].Bar
Also - do you perhaps have a local variable called ag? This would take precedence.
Can you post code that demonstrates this problem happening?
As an aside; note that both static fields and arrays have various associated complexities if your app gets complex... you might want to consider re-factoring them.
The following works fine:
static class logss_EventAnalyzer {
static string[] tabEventsString = {"abc","def","ghi"};
static string ag;
static void Main() {
ag = logss_EventAnalyzer.tabEventsString[0];
System.Console.WriteLine(ag);
}
}
If you are doing something radically different, you're going to have to give us a clue...
When you have a breakpoint at the line in question, does ag get a value assigned?
I suspect that in some other part of your code you're setting ag to null unintentionally, or perhaps you're assigning ag before logss_EventAnalyzer.tabEventsString[0] is given a non-null value.
If you give more details, I can give a better answer.
The first entry of logss_EventAnalyzer.tabEventsString is containing a string assigned to a null value. You have to look at the stacktrace to see which object is added as 1st entry. This object could be null assigned.

Categories

Resources