I'm new to C#.
I know in vb.net, i can do this:
Dim guid as string = System.Guid.NewGuid.ToString
In C#, I'm trying to do
String guid = System.Guid.NewGuid().ToString;
but i get an "Cannot convert method group 'ToString' to non-delegate type 'string'. Did you intend to invoke the method?" error.
According to MSDN the method Guid.ToString(string format) returns a string representation of the value of this Guid instance, according to the provided format specifier.
Examples:
guidVal.ToString() or guidVal.ToString("D") returns 32 hex digits
separated by hyphens: 00000000-0000-0000-0000-000000000000
guidVal.ToString("N") returns 32 hex digits:00000000000000000000000000000000
guidVal.ToString("B") returns 32 hex digits separated by hyphens, enclosed in braces:{00000000-0000-0000-0000-000000000000}
guidVal.ToString("P") returns 32 hex digits separated by hyphens, enclosed in parentheses: (00000000-0000-0000-0000-000000000000)
You're missing the () after ToString that marks it as a function call vs. a function reference (the kind you pass to delegates), which incidentally is why c# has no AddressOf operator, it's implied by how you type it.
Try this:
string guid = System.Guid.NewGuid().ToString();
Here are examples of output from each of the format specifiers:
N: cd26ccf675d64521884f1693c62ed303
D: cd26ccf6-75d6-4521-884f-1693c62ed303
B: {cd26ccf6-75d6-4521-884f-1693c62ed303}
P: (cd26ccf6-75d6-4521-884f-1693c62ed303)
X: {0xcd26ccf6,0x75d6,0x4521,{0x88,0x4f,0x16,0x93,0xc6,0x2e,0xd3,0x03}}
The default is D.
Run this yourself.
In Visual Basic, you can call a parameterless method without the braces (()). In C#, they're mandatory. So you should write:
String guid = System.Guid.NewGuid().ToString();
Without the braces, you're assigning the method itself (instead of its result) to the variable guid, and obviously the method cannot be converted to a String, hence the error.
Did you write
String guid = System.Guid.NewGuid().ToString;
or
String guid = System.Guid.NewGuid().ToString();
notice the parenthesis.
You need
String guid = System.Guid.NewGuid().ToString();
String guid = System.Guid.NewGuid().ToString();
Otherwise it's a delegate.
you are missing () on the end of ToString.
Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
string guidValue = guidId.ToString("D"); //return with hyphens
Following Sonar rules, you should whenever you can try to protect yourself, and use
System.globalisation whenever it's possible like for DateTime.ToString().
So regarding the other answers you could use:
guid.ToString("", CultureInfo.InvariantCulture)
where "" can be replaces by : N, D, B , P and X for more infos see this comment.
Example here
Related
I want to do the following but I get this
Error: an Implicit conversion from type Char[] to string is not
possible.
string Pattern2 = (Convert.ToDateTime(currMail.CreationTime).ToString(" dd-MMM-yyyy HH-mm")).ToArray();
Does anybody have any idea as on how to deal with this?
Remove .ToArray():
string Pattern2 = Convert.ToDateTime(currMail.CreationTime).ToString("dd-MMM-yyyy HH-mm");
As the other answers point out, your call to ToArray is not just unnecessary, it is in this case actively harmful. You already have a string in hand, you need a string, so don't convert the string to an array of char; just use the string.
However, for your future reference it is possible to convert an array of char to a string, just not via an implicit or explicit conversion. The syntax for that is:
char[] characters = whatever;
string str = new String(characters);
Finally, the documentation is here:
http://msdn.microsoft.com/en-us/library/vstudio/s1wwdcbf.aspx
Beginners should familiarize themselves with this documentation; there's a lot of good stuff in there.
Looks like you don't need to use .ToArray() method at all. You already using .ToString() method for assigning to your Pattern2 variable.
Just use as;
string Pattern2 = Convert.ToDateTime(currMail.CreationTime).ToString("dd-MMM-yyyy HH-mm");
string Pattern2 = Convert.ToDateTime(currMail.CreationTime).ToString(" dd-MMM-yyyy HH-mm");
You assign a char[] to a string, which requires conversion from the char[] to a string. As the error says, this is not done implicitly, i.e. behind the scenes. This is done to prevent silly mistakes.
You are expected to make an explicit conversion (create a string from the array and then assign it).
In your case you have a string and convert it to an array before assigning it to Pattern2. Just don't convert the string to an array.
string Pattern2 = (Convert.ToDateTime(currMail.CreationTime).ToString(" dd-MMM-yyyy HH-mm"));
static void Main(string[] args)
{
string str_val = "8584348,894";
//int prefix = Convert.ToInt32(str_val[0]); //prefix = 56 O_o
//int prefix = (int)str_val[0]; //what, again 56? i need 8!
int prefix = Convert.ToInt32("8"); //at least this works -_-
}
Any idea how to convert first symbol to right numeric value?
If you use:
Convert.ToInt32(str_val[0]);
then you are actually calling the overload:
Convert.ToInt32(char val);
which gives the Unicode/Ascii number of character being passed as a parameter.
If you want to convert first character, you need to force it to be a string type:
Convert.ToInt32(str_val.Substring(0, 1));
This way you call the overload:
Convert.ToInt32(string val);
which actually do what you want (convert string value to int value that this string represents).
Your trying to parse a string but passing in a char. Convert the character to a string first.
int prefix = Convert.ToInt32(str_val[0].ToString());
So the character value of 8 is the ASCII value 56, what you want to do is inteprete the value as a string rather than an ASCII Value. By using the .ToString() method you are converting the character into a null terminated string, which can be read by the ToInt32 method.
By doing this way Convert.ToInt32(str_val[0]) you are reading the character at a index of the string that converts the char to int. the int is the ascii for it
Like Bridge mentioned, it's getting the ASCII value. When you use the indexer on the string class to get just a character, it returns it as a char. If you read the char documentation you'll see that it is internally stored as a numeric UTF-16 value. It also has implicit conversions to and from most numeric types, which extract the UTF-16 value, or convert the numeric form into the character form. That's what you're doing.
What you mean to do is parse it as an int, not get the numeric representation of the UTF-16 value. That's where the Convert answers all come in.
Int32.Parse(str_val[0])
Will give you number in string.
I want to convert a thousand separated value to integer but am getting one exception.
double d = Convert.ToDouble("100,100,100");
is working fine and getting d=100100100
int n = Convert.ToInt32("100,100,100");
is getting one format exception
Input string was not in a correct format
Why?
try this:
int i = Int32.Parse("100,100,100", NumberStyles.AllowThousands);
Note that the Parse method will throw an exception on an invalid string, so you might also want to check out the TryParse method as well:
string s = ...;
int i;
if (Int32.TryParse(s, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out i))
{
// if you are here, you were able to parse the string
}
What Convert.ToInt32 is actually calling in your example is Int32.Parse.
The Int32.parse(string) method only allows three types of input: white space, a sign, and digits. In the following configuration [ws][sign]digits[ws] (in brackets are optional).
Since your's contained commas, it threw an exception.
Because you're supposed to specify a string containing a plain integer number (maybe preceded by +/- sign), with no thousands separator. You have to replace the separator befor passing the string to the ToInt32 routine.
You can't have separators, just numbers 0 thru 9, and an optional sign.
http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx
I am currently using the following line:
w.Write(DateTime.Now.ToString("MM/dd/yyyy,HH:mm:ss"));
and it gives and output like:
05/23/2011,14:24:54
What I need is quotations around the date and time, the output should look like this:
"05/23/2011","14:24:54"
any thoughts on how to "break up" datetime, and get quotes around each piece?
Try String.Format:
w.Write(String.Format("\"{0:MM/dd/yyyy}\",\"{0:HH:mm:ss}\"", DateTime.Now));
DateTime.Now.ToString("\\\"MM/dd/yyyy\\\",\\\"HH:mm:ss\\\"")
This will do the trick, too.
string format = #"{0:\""MM/dd/yyyy\"",\""HH:mm:ss\""}" ;
string s = string.Format(format,DateTime.Now) ;
as will this:
string format = #"{0:'\""'MM/dd/yyyy'\""','\""'HH:mm:ss'\""'}" ;
string s = string.Format(format,DateTime.Now) ;
and this
string format = #"{0:""\""""MM/dd/yyyy""\"""",""\""""HH:mm:ss""\""""}" ;
string s = string.Format(format,DateTime.Now) ;
The introduction of a literal double quote (") or apostrophe (') in a DateTime or Numeric format strings introduces literal text. The embedded literal quote/apostrophe must be balanced — they act as an embedded quoted string literal in the format string. To get a double quote or apostrophe it needs to be preceded with a backslash.
John Sheehan's formatting cheatsheets makes note of this...feature, but insofar as I can tell, the CLR documentation is (and always has been) incorrect WRT this: the docs on custom date/time and numeric format strings just says that "[any other character] is copied to the result string unchanged.".
string part1 = DateTime.Now.ToString("MM/dd/yyyy");
string part2 = DateTime.Now.ToString("HH:mm:ss");
Console.WriteLine("\""+part1+"\",\""+part2+"\"");
Works just fine. May not be the best way though
I'm not sure about the type of w but if it supports the standard set of Write overloads the following should work.
w.Write(#"""{0}""", DateTime.Now.ToString(#"MM/dd/yyyy"",""HH:mm:ss")));
If not then you can do the following
var msg = String.Format(#"""{0}""", DateTime.Now.ToString(#"MM/dd/yyyy"",""HH:mm:ss"))));
w.Write(msg);
The following version, though obvious, will not work:
w.Write(DateTime.Now.ToString("\"MM/dd/yyyy\",\"HH:mm:ss\""));
This will output:
MM/dd/yyyy,HH:mm:ss
So don't do that.
dsgetQuesTypeID = objdalQuesTypeID.GetQuesTypeID(int.Parse(QuesTypeID)); //error here
Whats wrong ?
if you see the int.Parse in metadata explorer
//
// Summary:
// Converts the string representation of a number to its 32-bit signed integer
// equivalent.
//
// **Parameters:
// s:
// A string containing a number to convert.**
//
// Returns:
// A 32-bit signed integer equivalent to the number contained in s.
//
public static int Parse(string s);
it requires a string input to be parsed , but QuesTypeID is int so that's why no overloaded method is found so to correct the problem , you need to do following
int.Parse(QuesTypeID.ToString());
You have a member with the same name QuesTypeID as the name of the variable passed to the method. One is int and one is String. Try to rename the variable from the method to something else, like: quesTypeID. I think this would solve your problem. Also you should use Int.TryParse instead of Int.Parse.
You maybe passing null value into GetQuesTypeID(string QuesTypeID)