C# get string name's name [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get variable name using reflection?
How to get the string name's name not the value of the string
string MyString = "";
Response.Write(MyString.GetType().Name);//Couldn't get the string name not the value of the string
The result should display back the string name "MyString"
I've found some suggested codes and rewrite it to make it shorter but still didn't like it much.
static string VariableName<T>(T item) where T : class
{
return typeof(T).GetProperties()[0].Name;
}
Response.Write(VariableName(new { MyString }));
I am looking another way to make it shorter like below but didn't how to use convert the current class so i can use them in the same line
Response.Write( typeof(new { MyString }).GetProperties()[0].Name);

While Marcelo's answer (and the linked to "duplicate" question) will explain how to do what you're after, a quick explanation why your code doesn't work.
GetType() does exactly what it says: it gets the Type of the object on which it is called. In your case, it will return System.String, which is the Type of the object referenced by your variable MyString. Thus your code will actually print the .Name of that Type, and not the name of the variable (which is what you actually want.)

Related

C# Selecting part of string when there is a matching result in part of the string [duplicate]

This question already has answers here:
Get URL parameters from a string in .NET
(17 answers)
Closed 5 years ago.
I have a string which basically looks like this:
/giveaway/host/setup/ref=aga_h_su_dp?_encoding=UTF8&value_id=1484778065
The trick here is that the length of the string can vary and will change... However the part with "value_id=something" always stays same... So the problem that I ran in was that I can do something like this:
var myId = string.SubString(30,45);
to get the value after value_id= /*this one here*/
I'm thinking that this can be solved by regex or some other way, but I'm not too sure how to write such one. Can someone help me out?
Could you try this. If your value_id always the last of your string you can use this.
var str = "/giveaway/host/setup/ref=aga_h_su_dp?_encoding=UTF8&value_id=1484778065";
var valueId = str.Split('=').LastOrDefault();
Result : 1484778065
Hope it's help to you
You can split by 'value_id='
string[] tokens = str.Split(new[] { "value_id=" }, StringSplitOptions.None);
if(tokens.Length>1){
//parse tokens[1] with the value
}

c# replace character by an empty string [duplicate]

This question already has answers here:
C# string replace does not actually replace the value in the string [duplicate]
(3 answers)
Closed 5 years ago.
I'm getting a string from a Json :
var value = JsonObject["price"]; //value = "1,560";
i'm trying to replace the ',' with an empty string :
value.Replace(",",string.Empty);
but i'm still getting the value with "," that's so strange and i'm stuck at it
thanks in advance
value = value.Replace( ", ", string.Empty);
strings in .net are immutable.
Per the documentation for String.Replace:
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
It gives you a new string; it doesn't modify the existing one. So you need to assign the result to a variable:
value = value.Replace(",", string.Empty);

C# - Converting from string to my object

In my code I load a text file and read it, looking for specific parameters. After I get them, I save them as string, and now I need to send them to a set-method, that only gets MyProperties type variables. ("MyProperties" is an enum class, and the method that receives the parameter needs to get an enum of this type)
So my question is: how can I convert them from string to MyProperties type?
Reading the file:
string input = File.ReadAllText("C:/avi/properties/" + propertiesFile);
After I get a parameter I need, I save it in a string var named mode.
string mode; // ---> Needs to be "MyProperties mode;"
vpa.Set(MyProperties.Mode, mode);
Solutions like checking if (mode.equals("string")) or "switch" are too long because there is a lot to check.
Been able to find an answer on another post, this is what i used:
TypeConverter converter = TypeDescriptor.GetConverter(type);
MyProperties prop = (MyProperties)converter.ConvertFrom(mode);

How to print my methods name [duplicate]

This question already has answers here:
Can you use reflection to find the name of the currently executing method?
(19 answers)
Closed 6 years ago.
I am new on coding just need find out if it is possible to get methods name and print using console.write. Here I have sample class and I want to grab "myName" so I can use it to print.
using System;
namespace Tests
{
class Class1
{
public void myName()
{
Console.Write(myName);
}
}
}
Simply use the nameof keyword
Console.Write(nameof(myName));
You can get like this for full information:
string method = string.Format("{0}.{1}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodBase.GetCurrentMethod().Name);
And return this string. Using call this within the metod.
Or short version just for name method, what you want:
string method =System.Reflection.MethodBase.GetCurrentMethod().Name;

How to preserve "{0}" after two string.Format calls [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to add { in String Format c#
When i'm rewriting always the same thing, i'm used to write what I call a string pattern of it.
Let's say I would like to do SQL injection to extend ORM functionality...
protected static string FULLTEXTPATTERN = "EXISTS CONTAINSTABLE([{0}],*,'\"{1}\"') WHERE [key] = {0}.id;
And usually I got the table name and value that i combine in a string.format(FULLTEXTPATTERN ,...) and everything is fine.
Imagine now, I have to do that in two time. first injecting the table name, then the value I search for. So I would like to write something like:
protected static string FULLTEXTPATTERN = "EXISTS CONTAINSTABLE([{0}],*,'\"{{0}}/*Something that returns {0} after string.format*/\"') WHERE [key] = {0}.id;
...
var PartialPattern= string.fomat(FULLTEXTPATTERN, "TableX");
//PartialPattern = "EXISTS CONTAINSTABLE([TableX],*,'\"{0}\"') WHERE [key] = {0}.id"
...
//later in the code
...
var sqlStatement = string.format(PartialPattern,"Pitming");
//sqlStatement = "EXISTS CONTAINSTABLE([TableX],*,'\"Pitming\"') WHERE [key] = {0}.id"
Is there a way to do it ?
Logic says that you would simply put {{{0}}} in the format string to have it reduce down to {0} after the second string.Format call, but you can't - that throws a FormatException. But that's because you need yet another { and }, otherwise it really is not in the correct format :).
What you could do - set your full format to this (note the 4 { and } characters at the end):
"EXISTS CONTAINSTABLE([{0}],*,'\"{{0}}\"') WHERE [key] = {{{{0}}}}.id";
Then your final string will contain the {0} you expect.
As a proof - run this test:
[TestMethod]
public void StringFormatTest()
{
string result = string.Format(string.Format(
"{0} {{0}} {{{{0}}}}", "inner"), "middle");
Assert.AreEqual("inner middle {0}", result);
}
Is it possible to delay generating SQL to the point at which you have all the required inputs so that you can use one call to String.Format() and multiple fields?
Alternatively, you could you build the query iteratively using a StringBuilder rather than String.Format().

Categories