Posts tagged "CSharp"
Hex String to Color (ARGB)
public Color HexStringToColor(string hex)
{
hex = hex.Replace("#", "").ToLowerInvariant();
if (hex.Length == 6)
{
hex = "ff" + hex;
}
else if (hex.Length != 8)
{
throw new Exception(hex + "
is not a valid 6 or 8-place
hexadecimal color code.");
}
int a, r, g, b;
a = Convert.ToInt32(hex.Substring(0, 2), 16);
r = Convert.ToInt32(hex.Substring(2, 2), 16);
g = Convert.ToInt32(hex.Substring(4, 2), 16);
b = Convert.ToInt32(hex.Substring(6, 2), 16);
return Color.FromArgb(a, r, g, b);
}
(this assumes input is correct format - either ‘#FFFFFF’ or ‘FFFFFF’)
NSDate to DateTime and Back
- Reference Date is January 1, 2001 0:00:00 UTC (GMT)
- It’s important to note the Local Time Zone vs. UTC/GMT
NSDate to DateTime
public static DateTime NSDateToDateTime(NSDate date)
{
DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime(
new DateTime(2001, 1, 1, 0, 0, 0) );
return reference.AddSeconds(date.SecondsSinceReferenceDate);
}
DateTime to NSDate
public static NSDate DateTimeToNSDate(DateTime date)
{
DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime(
new DateTime(2001, 1, 1, 0, 0, 0) );
return NSDate.FromTimeIntervalSinceReferenceDate(
(date - reference).TotalSeconds);
}
Integer to Ordinal
public string AddOrdinal(int num)
{
switch(num % 100)
{
case 11:
case 12:
case 13:
return num.ToString() + "th";
}
switch(num % 10)
{
case 1:
return num.ToString() + "st";
case 2:
return num.ToString() + "nd";
case 3:
return num.ToString() + "rd";
default:
return num.ToString() + "th";
}
}
age from birthday
Rather than dividing figures by a fixed number days (which ignores special cases like leap years), I find this method quite reliable.
//Given DateTime birthday
TimeSpan span = DateTime.Now - birthday;
DateTime time = DateTime.MinValue + span;
int age = time.Year - 1;
System.IO.Path.Combine Behavior
When using Path.Combine, you should be aware of the behavior that if the second parameter has a leading slash, it will ignore the first parameter.
Given the following:
string root = "c:\";
string path = "test.txt";
string lead = "\test.txt";
We get the following results:
using System.IO;
…
Path.Combine(root, path); // ‘c:\test.txt’
Path.combine(root, lead); // ‘\test.txt’
Safe Casting
Use the as keyword.
MyClass castedObject = obj as MyClass;
This won’t throw a class cast exception. Instead, castedObject will return null if obj isn’t a MyClass.
Chain ?? Operators
You can use multiple ?? operators to chain multiple null comparisons:
string text = value1 ?? value2 ?? String.Empty;
Normalizing & Comparing Strings
When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons.
[source: CLR via C# ]